【问题标题】:Get all matches using regexp preg_match() function in PHP在 PHP 中使用正则表达式 preg_match() 函数获取所有匹配项
【发布时间】:2015-02-26 11:30:25
【问题描述】:

我正在使用preg_match 在具有特定 src 或 href 模式的 xml 中搜索 img 元素。示例:< img src= "level1/level2/2837"< img href ='level1/level2/54322'

preg_match('/< *\/? *' // Begining of xml element
  . 'img' // "img" atribute
  . '[^>]*' // Any character except >
  . '(?:src|href) *= *' // src or href attribute with possible spaces between =
  . '(?:"|\')level1\/level2\/(\d+)(?:"|\')/', // "level1/level2/2837"
  $subject, $matches);

它有效,但只返回第一个匹配项。

例如,如果主题有以下内容:

$subject = "< img  src= 'level1/level2/2837'/> <p>something</p> < img  href ='level1/level2/54322'";

我得到的结果是:

$matches => Array 
    ( 
        [0] => '< img  src= "level1/level2/2837"' 
        [1] => '2837' 
    ) 

如何获取$matches 数组中的所有匹配项?

我已经使用simplexml_load_string 来实现此目的,但想了解正则表达式如何与preg_match 一起使用。

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用preg_match_all 而不是preg_match

    【讨论】:

    • @AvinashRaj 好的.. 你是对的,这将匹配单个字符谢谢。我正在更新它
    【解决方案2】:

    您需要将 ["|'] 转为 (?:"|') 。这个['|"] 将匹配'|"。而且您还需要使用preg_match_all 才能进行全局匹配。

    preg_match_all('/< *\/? *'
      . 'img'
      . '[^>]*'
      . '(?:src|href) *= *'
      . '(?:"|\')level1\/level2\/(\d+)(?:"|\')/', 
      $subject, $matches);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 2010-10-13
      • 1970-01-01
      • 2012-07-23
      • 2020-07-19
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      相关资源
      最近更新 更多