dotelauv682684 2013-04-13 13:45
浏览 42
已采纳

PHP,Regex和preg_match

I am trying to extract substrings matching given regex expression from the string below:

"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 does match it as expected. However, for some reason I can only access the first parsed value. Even though the counter (count($matches)) states there are two results, see the output.

$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">';

The source:

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);

The output:

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

Thanks, LG

  • 写回答

3条回答 默认 最新

  • drozwmi5440 2013-04-13 13:47
    关注

    Use preg_match_all to get all matches. preg_match will only return the first match. Count will return two because you capture a group.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序