【问题标题】:How to get the pattern that matched a string based on the string order如何根据字符串顺序获取匹配字符串的模式
【发布时间】:2017-10-25 23:11:30
【问题描述】:

假设我们有以下数组

$regexList = ['/def/', '/ghi/', '/abc/'];

和下面的字符串

$string = '

{{abc}}
{{def}}
{{ghi}}

';

思路是从上到下遍历字符串,依靠正则表达式列表,找到结果,用匹配出现的模式的大写内容替换无论 regexList array 是什么顺序,都在字符串顺序上。

所以,这就是我想要的输出:

  • ABC 匹配:/abc/;
  • DEF 匹配:/def/;
  • GHI 匹配:/ghi/;

至少

  • ABC 匹配模式:2;
  • DEF 匹配:0;
  • GHI 匹配:1;

这是我正在尝试的代码:

$regexList = ['/def/', '/ghi/', '/abc/'];

$string = '

abc
def
ghi

';

$string = preg_replace_callback($regexList, function($match){
  return strtoupper($match[0]);
}, $string);

echo '<pre>';
var_dump($string);

这个输出只是:

string(15) "

ABC
DEF
GHI

"

如何以 $string 顺序(从上到下)获得与这些字符串匹配的偏移量或模式?谢谢。

【问题讨论】:

标签: php regex preg-replace-callback


【解决方案1】:

不要使用正则表达式数组,而是使用单个正则表达式与替代和捕获组。然后就可以看到哪个捕获组不为空了。

$regex = '/(def)|(ghi)|(abc)/';
$string = preg_replace_callback($regex, function($match) {
    for ($i = 1; $i < count($match); $i++) {
        if ($match[$i]) {
            return strtoupper($match[$i]) . " was matched by pattern " . $i-1;
        }
    }
}, $string);

【讨论】:

  • 你的代码输出:string(24) " {{-1}} {{-1}} {{-1}} "
【解决方案2】:

@Barmar 是对的,但我要稍微修改一下:

$order = [];

$string = preg_replace_callback('/(def)|(ghi)|(abc)/', function($match) use (&$order) {
    end($match);
    $order[key($match)] = current($match);
    return strtoupper($match[0]);
}, $string);

print_r($order);

输出:

Array
(
    [3] => abc
    [1] => def
    [2] => ghi
)

【讨论】:

  • 谢谢!就是这样!
猜你喜欢
  • 2017-02-05
  • 2014-02-06
  • 1970-01-01
  • 2021-11-23
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多