【问题标题】:PHP preg_match_all matches correctly but only gives one matchPHP preg_match_all 匹配正确但只给出一个匹配
【发布时间】:2014-04-08 16:11:19
【问题描述】:

我正在使用这个正则表达式从用户提交的内容中提取部分:

preg_match_all("~\[section name=[\"|'](.*?)[\"|']\](.*?)\[\/section\]~", $content, $matches, PREG_SET_ORDER);

目的是让非技术用户轻松创建不同的命名部分。据我所知,PHP 的 bbcode 解析器不允许我以这种方式将内容和属性值提取到数组中。

我不确定为什么preg_match_all parsing, only one match 接受的答案被接受,因为它表明 preg_match_all 默认情况下不全局匹配,并且建议的g 标志似乎无效。

当前函数正确匹配,使得:

[section name="one"]this is section one[/section]

进入$matches:

array (size=1)
    0 => 
        array (size=3)
            0 => string '[section name="one"]this is section one[/section]'
            1 => string 'one'
            2 => string 'this is section one'

这是期望的行为。

但是,它不会向$matches 数组添加更多匹配项,只会添加第一个匹配项。

我需要做什么才能让$matches 填充给定字符串中的所有匹配项?

【问题讨论】:

  • 你真的很幸运能够逃脱和使用|[]。您应该花一些时间来学习使用它们的正确方法。
  • @pguardiario 你能详细说明一下吗?
  • 例如 ("|') 是一个交替组。您正在使用 ["|'] 这是一个带有文字 | 的字符类。在里面。如果你离开了 |出它会做与 ("|') 相同的事情。而且你正在转义 /,当你使用 / 作为分隔符时这很重要,但在其他方面是不必要的。

标签: php regex


【解决方案1】:

很奇怪,因为当我运行脚本时:

    $content = '[section name="one"]this is section one[/section]<br />[section name="two"]this is section two[/section]';
    preg_match_all("~\[section name=[\"|'](.*?)[\"|']\](.*?)\[\/section\]~", $content, $matches, PREG_SET_ORDER);
    print_r($matches);

打印出来:

Array
(
[0] => Array
    (
        [0] => [section name="one"]this is section one[/section]
        [1] => one
        [2] => this is section one
    )

[1] => Array
    (
        [0] => [section name="two"]this is section two[/section]
        [1] => two
        [2] => this is section two
    )

)

【讨论】:

  • 问题是内容包含空格(换行符),正则表达式中的.* 没有涵盖。更新的正则表达式模式是:~\[section name=[\"|'](.*?)[\"|']\]([\s\S]+?)\[\/section\]~ 这允许内容中有空格并正确找到所有匹配项。您对一行输入的回答促使我考虑这个问题。
  • 很高兴我能以任何方式提供帮助。
猜你喜欢
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多