如何获得基于字符串顺序匹配的字符串模式
问题描述:
假设我们有跟随阵列:如何获得基于字符串顺序匹配的字符串模式
$regexList = ['/def/', '/ghi/', '/abc/'];
和串波纹管:
$string = '
{{abc}}
{{def}}
{{ghi}}
';
的想法是要从上到下经过字符串并依靠正则表达式列表,找到结果并用大写内容替换为模式为tha t无论按照什么顺序匹配发生的字符串顺序regexListarray是。
所以,这就是我想要的输出:
- ABC被匹配:/ ABC /;
- DEF被匹配:/ def /;
- GHI匹配:/ ghi /;
或在leats
- 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
"
如何才能得到补偿或模式匹配在$这些字符串字符串顺序(从上到下)?谢谢。
答
@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
)
+0
谢谢!而已! – e200
答
请勿使用正则表达式数组,请使用具有替代方法和捕获组的单个正则表达式。然后你可以看到哪个捕获组不是空的。
$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);
的[获取在预浸\ _replace \当前指数可能的复制_callback?](https://stackoverflow.com/questions/8484062/getting-the-current-index-in-preg-replace-callback) – RST
@RST:这与问题无关。 – Toto