【问题标题】:php preg_match_all numbers in parenthesesphp preg_match_all 括号中的数字
【发布时间】:2012-07-20 13:22:29
【问题描述】:

我正在尝试加载一个远程网站并获取括号内的所有数字。但最终发生的是它只匹配最后一个值。

我的正则表达式错了吗?我使用了正确的标志吗?

我已经在第二个 $html 变量中添加了它应该匹配的示例。

    //$html = file_get_contents("http://example.com/test.html");

    $html = "(1234) (12) (1)  \r\n  (1346326)";
    preg_match_all("^[(\d)]+$^", $html, $matches, PREG_PATTERN_ORDER);
    print_r($matches);
    echo "<br>";
    foreach ($matches as $val) {
        echo "matched: " . $val[0] . "\n";

    }

谢谢。

【问题讨论】:

    标签: php regex preg-match-all numeric


    【解决方案1】:

    怎么样:

    preg_match_all("/\((\d+)\)/", $html, $matches, PREG_PATTERN_ORDER); 
    print_r($matches[1]);
    

    【讨论】:

    • 感谢您的成功。我不得不调整 foreach code $html = "(1234) (12) (1) \r\n (1346326)"; preg_match_all("/((\d+))/", $html, $matches, PREG_PATTERN_ORDER); print_r($matches[1]);回声“
      ”; foreach ($matches[1] as $val) { echo "matched: " . $val 。 "
      \n"; }code
    【解决方案2】:

    我看到两个可能的问题。

    首先,您从 start(^) 到 end($) 进行匹配,它只会匹配恰好位于行首和行尾之间的内容。

    其次,您很可能希望使用 /gs 正则表达式参数将其全部输入。

    preg_match_all("/\b(\d+)\b/gs" ...
    

    【讨论】:

    • PHP 没有“g”修饰符。 preg_match_all() 始终是全局的。
    猜你喜欢
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多