我想做一些类似于问题的事情preg_match_all 如何获得*所有*组合?甚至重叠的 https://stackoverflow.com/questions/22454032/preg-match-all-how-to-get-all-combinations-even-overlapping-ones并找到给定模式的所有匹配项,即使它们重叠(例如,将字符串 ABABA 与模式 ABA 匹配应返回 2 个匹配项,而不仅仅是第一个匹配项)。
但我有一个额外的限制:我的模式可以以重复说明符结束。让我们使用+
举个例子:这意味着模式/A+/
和主题"AA"
应返回 3 个匹配项:
- Match
"AA"
从索引 0 开始
- Match
"A"
从索引 1 开始
- Match
"A"
从索引 0 开始
根据上述问题建议的解决方案,以下模式无法匹配所有 3 个结果:
- Pattern
/(?=(A+))/
仅查找前 2 个匹配项,但不查找最后一个匹配项
- Pattern
/(?=(A+?))/
仅查找最后 2 个匹配项,但不查找第一个匹配项
我现在唯一的解决方法是保留贪婪版本,并尝试对每个匹配减去最后一个字符应用模式,重复此操作直到不再匹配,例如:
$all_matches = array ();
$pattern = 'A+';
preg_match_all("/(?=($pattern))/", "AA", $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
do {
$all_matches[] = $match[1];
$subject = substr($match[1], 0, -1);
}
while (preg_match("/^($pattern)/", $subject, $match));
}
有没有更好的解决方案可以使用 preg_match_all 或类似的方法来实现此目的?
您希望在一个索引处获得多个匹配项,这对于 1 个正则表达式匹配操作来说是不可能的。你实际上需要
- 从字符串中查找子字符串的所有组合
- 只保留那些完全符合您的模式的。
See the PHP demo http://ideone.com/dbpOdk:
function find_substrings($r, $s) {
$res = array();
$cur = "";
$r = '~^' . $r . '$~';
for ($q = 0; $q < strlen($s); ++$q) {
for ($w = $q; $w <= strlen($s); ++$w) {
$cur = substr($s, $q, $w-$q);
if (preg_match($r, $cur)) {
array_push($res, $cur);
}
}
}
return $res;
}
print_r(find_substrings("ABA", "ABABA"));
// => Array ( [0] => ABA [1] => ABA )
print_r(find_substrings("A+", "AA"));
// => Array ( [0] => A [1] => AA [2] => A )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)