【问题标题】:Parsing html string in php using regular expression [duplicate]使用正则表达式在php中解析html字符串[重复]
【发布时间】:2013-02-19 21:50:15
【问题描述】:

我想用 php 解析一个 html 字符串(简单数字匹配)。

<i>1002</i><i>999</i><i>344</i><i>663</i>

我希望结果是一个数组。例如:[1002,999,344,633,...] 我试过这样:

<?php
    $html="<i>1002</i><i>999</i><i>344</i><i>663</i>";
    if(preg_match_all("/<i>[0-9]*<\/i>/",$html, $matches,PREG_SET_ORDER))
        foreach($matches as $match) {
            echo strip_tags($match[0])."<br/>";
        }
?>

我得到了我想要的确切输出。

1002
999
344
663

但是,当我通过对正则表达式进行小的更改来尝试相同的代码时,我得到了不同的答案。

像这样:

<?php
    $html="<i>1002</i><i>999</i><i>344</i><i>663</i>";
    if(preg_match_all("/<i>.*<\/i>/",$html, $matches,PREG_SET_ORDER))
        foreach($matches as $match) {
            echo strip_tags($match[0])."<br/>";
        }
?>

输出:

1002999344663

(正则表达式匹配整个字符串。)

现在我想知道为什么我会变成这样? 如果使用.*(零个或多个)而不是[0-9]*,有什么区别?

【问题讨论】:

  • * 默认是贪婪的。
  • K.那么什么是'?在那里。
  • @VishalVijay:我会在回答中解释:P

标签: php html regex parsing


【解决方案1】:

您的正则表达式中的.* 匹配任何 字符([0-9]* 仅匹配数字,&lt;/i&gt;&lt;i&gt; 不是数字)。正则表达式/&lt;i&gt;.*&lt;\/i&gt;/ 匹配:

<i>1002</i><i>999</i><i>344</i><i>663</i>
^ from here ------------------- to here ^

因为,整个字符串都在 &lt;i&gt;&lt;/i&gt; 内。

这是因为* 是贪婪的。它需要 max 个可以匹配的字符。

要解决您的问题,您需要使用.*?。这使得它可以匹配最少个字符。

正则表达式 /&lt;i&gt;.*?&lt;\/i&gt;/ 将按您的意愿工作。

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多