【问题标题】:PHP, Regex and preg_matchPHP、正则表达式和 preg_match
【发布时间】:2013-04-05 23:45:44
【问题描述】:

我正在尝试从下面的字符串中提取与给定正则表达式匹配的子字符串:

“Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">

Regex 确实符合预期。但是,由于某种原因,我只能访问第一个解析值。即使计数器 (count($matches)) 表明有两个结果,请参阅输出。

$value = 'Lorem ipsum dolor sit amet. <xy:abc_ref d_id="1234">Lorem ipsum dolor sit amet. <xy:abc_ref d_id="5678">Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">';

来源:

function test($value)
{
    $RegEx = '/<xy:abc_ref ([^>]{0,})>/';       
    $n = preg_match($RegEx,$value,$matches);
    print("Results count: " . count($matches)."<br>");
    print("matches[0]: " . $matches[0]."<br>");
    print("matches[1]: " . $matches[1]."<br>");
    print("matches[2]: " . $matches[2]."<br>");
}
echo test($value);

输出:

Results count: 2
matches[0]:
matches[1]: d_id="1234"
matches[2]: 

谢谢,LG

【问题讨论】:

标签: php regex


【解决方案1】:

使用preg_match_all 获取所有匹配项。 preg_match 只会返回第一个匹配项。 Count 将返回 2,因为您捕获了一个组。

【讨论】:

    【解决方案2】:

    您必须改用preg_match_all

    【讨论】:

      【解决方案3】:
      function test($value)
      {
          $RegEx = '/<xy:abc_ref ([^>]{0,})>/';       
          $n = preg_match_all($RegEx,$value,$matches);
          print("Results count: " . count($matches[1])."<br>");
          print("matches[0]: " . $matches[1][0]."<br>");
          print("matches[1]: " . $matches[1][1]."<br>");
          print("matches[2]: " . $matches[1][2]."<br>");
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 2012-01-14
        相关资源
        最近更新 更多