【问题标题】:PHP regex match multiple tags within a string and add to arrayPHP正则表达式匹配字符串中的多个标签并添加到数组
【发布时间】:2016-12-02 15:55:28
【问题描述】:

我有一个带有多个标签的字符串:

<item>foo bar</item> <item>foo bar</item>

我需要匹配每一个,它们可以在新行上并将它们添加到数组中,但它似乎无法匹配它们,我是正则表达式的新手,所以我不明白出了什么问题,解释一下就好了,谢谢!

preg_match_all('/<item>(.*)<\/item>/',$content,$matches);

目前,它在matches数组中返回两个空索引。

我也试过了:

<item>([\s\S]*)<\/item>

这匹配从第一个标签到最后一个标签,因此基本上抓住了所有内容。

【问题讨论】:

  • 这样试试preg_match_all('/(&lt;item&gt;(.*?)&lt;\/item&gt;)/',$content,$matches);
  • 如果问题只是关于正则表达式,那么.* 是贪婪的,想要它可以抓住的一切。根据new lines 的含义,这也可能表现不同。您可以使用一些修饰符来影响这些行为。查看Us 修饰符php.net/manual/en/reference.pcre.pattern.modifiers.php
  • @chris85 我无法将其解析为 XML,因为我将这些标签添加到 Magento 中的所见即所得编辑器中,作为静态块的动态内容的一种方式,因此基本上

    标签被包装在每个新行周围,它们不能被剥离,因为它们也可以嵌套在标签内的内容中。

  • 您在问题中显示的内容可以使用解析器完成。你能展示更多你在做什么吗?

标签: php arrays regex


【解决方案1】:

你可以用这个

preg_match_all('/&lt;item&gt;(.*?)&lt;\/item&gt;/',$content,$matches);

结果

 Array
 (
    [0] => Array
    (
        [0] => <item>foo bar</item>
        [1] => <item>foo bar</item>
    )

[1] => Array
    (
        [0] => foo bar
        [1] => foo bar
    )

)

我只在正则表达式中添加了?,它会查找最近的匹配项并获取它。

在这里阅读关于懒惰和贪婪的信息:What do lazy and greedy mean in the context of regular expressions?

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多