在 PHP 中使用正则表达式 preg_match() 函数获取所有匹配项

Get all matches using regexp preg_match() function in PHP

我正在使用 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);

它有效,但仅 returns 第一场比赛。

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

$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.

一起使用

使用preg_match_all instead of preg_match.

您需要将 ["|'] 改为 (?:"|') 。此 ['|"] 将匹配 '|"。而且您还需要使用 preg_match_all 来进行全局匹配。

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