PHP正则表达式-重复组匹配 [英] PHP Regular Expression - Repeating Match of a Group

查看:188
本文介绍了PHP正则表达式-重复组匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的字符串:

I have a string that may look something like this:

$r = 'Filed under: <a>Group1</a>, <a>Group2</a>';

这是到目前为止我正在使用的正则表达式:

Here is the regular expression I am using so far:

preg_match_all("/Filed under: (?:<a.*?>([\w|\d|\s]+?)<\/a>)+?/", $r, $matches);

我希望正则表达式位于()内部,以继续进行最后由+?指定的匹配.但这只是做不到. :: sigh ::

I want the regular expression to inside the () to continue to make matches as designated with the +? at the end. But it just won't do it. ::sigh::

任何想法.我知道必须有一种方法可以在一个正则表达式中执行此操作,而不是将其拆分.

Any ideas. I know there has to be a way to do this in one regular expression instead of breaking it up.

推荐答案

尝试:

<?php

$r = 'Filed under: <a>Group1</a>, <a>Group2</a>, <a>Group3</a>, <a>Group4</a>';

if(preg_match_all("/<a.*?>([^<]*?)<\/a>/", $r, $matches)) {
    var_dump($matches[1]); 
}

?>

输出:

array(4) {
  [0]=>
  string(6) "Group1"
  [1]=>
  string(6) "Group2"
  [2]=>
  string(6) "Group3"
  [3]=>
  string(6) "Group4"
}

由于您要在搜索中包括字符串"Filed under"以唯一标识匹配项,因此可以尝试一下,我不确定是否可以使用一次对preg_match的调用来完成

Since you want to include the string 'Filed under' in the search to uniquely identify the match, you can try this, I'm not sure if it can be done using a single call to preg_match

// Since you want to match everything after 'Filed under'
if(preg_match("/Filed under:(.*)$/", $r, $matches)) {
    if(preg_match_all("/<a.*?>([^<]*?)<\/a>/", $matches[1], $matches)) {
        var_dump($matches[1]); 
    }
}

这篇关于PHP正则表达式-重复组匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆