【问题标题】:regex to find string within square brackets []正则表达式在方括号 [] 中查找字符串
【发布时间】:2012-03-12 10:08:29
【问题描述】:

我想在下面的 html 字符串中捕获方括号内的文本。 但是我在下面的正则表达式并没有分别得到 'image' 和 imagealt' 而是返回 'image]" alt="[imagealt' 。如果我从字符串中取出 alt="[imagealt]" ,它会按照我的预期/想要返回。

$html = '<h2>[title]</h2>
<div class="content"><img src="[image]" alt="[imagealt]" /></div>
<div class="content">[text]</div>';

preg_match_all("^\[(.*)\]^",$html,$fields, PREG_PATTERN_ORDER);

echo "<pre>";
print_r($fields);
echo "</pre>";


Array
(
    [0] => Array
        (
            [0] => [title]
            [1] => [image]" alt="[imagealt]
            [2] => [text]
        )

    [1] => Array
        (
            [0] => title
            [1] => image]" alt="[imagealt
            [2] => text
        )

)

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你的正则表达式很贪心。你需要停止贪婪地做你想做的事。了解更多关于贪婪的信息here

    当匹配为贪婪时,它将忽略满足正则表达式的第一种情况,并继续尝试匹配,直到它消耗尽可能多的输入。

    通常这涉及添加?,但我不确定在 php 中,但您可以尝试:

    preg_match_all("^\[(.*?)\]^",$html,$fields, PREG_PATTERN_ORDER);
    

    【讨论】:

      【解决方案2】:
      preg_match_all("#\[[^\]]*\]#",$html,$fields, PREG_PATTERN_ORDER);
      

      ^ 插入符号用于标记字符串的开头,因此我使用#| 作为分隔符以避免混淆。另外,我使用[^\]*] 而不是.*?,因为它在到达] 的末尾时肯定会停止,而您需要. 上的惰性修饰符,甚至可能需要m 修饰符来确保如果您的属性决定包含换行符,它会捕获换行符。

      【讨论】:

        【解决方案3】:

        使用

             preg_match_all("^\[(.*?)\]^",$html,$fields, PREG_PATTERN_ORDER);
        

        额外的? 表示“非贪婪匹配”,它会在找到] 后停止

        【讨论】:

          猜你喜欢
          • 2022-01-20
          • 2015-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-09
          • 1970-01-01
          相关资源
          最近更新 更多