[英]php preg_match_all need multiple results
我想让preg_match_all
返回找到的所有模式,即使结果已经使用过。 下面的示例解决了这个问题。
$str = "whatever aaa 34567 aaa 56789 ll";
$pattern = '/.{0,100}\D[aaa]{3}\D{1}[0-9]{5}\D{1}/';
preg_match_all($pattern, $str, $amatches);
var_dump($amatches);
上面的结果返回一个数组元素。
0=> `whatever aaa 34567 aaa 56789 `
我想要的是2个数组元素。
0=> `whatever aaa 34567`
1=> `whatever aaa 34567 aaa 56789`
这更接近:
$str = "whatever aaa 34567 aaa 56789 ll";
$pattern = '/^((.*)\D[aaa]{3}\D{1}[0-9]{5}\D{1})?/';
preg_match($pattern, $str, $amatches);
var_dump($amatches);
回报
array(3) {
[0] => string(29) "whatever aaa 34567 aaa 56789 "
[1] => string(29) "whatever aaa 34567 aaa 56789 "
[2] => string(18) "whatever aaa 34567"
}
或仍使用preg_match_all:
$str = "whatever aaa 34567 aaa 56789 ll";
$pattern = '/^((.*)\D[aaa]{3}\D{1}[0-9]{5}\D{1})?/';
preg_match_all($pattern, $str, $amatches);
var_dump($amatches);
我认为正在发生的事情是您的。{0,100}正在被整个内容读取,而根本不允许正则表达式插入。 ? 确保它以您的图案结尾。
这是使用preg_replace_callback进行工作的替代解决方案。
\\b
表示单词边界,防止匹配“ xaaa 12345”,“ aaa 123456”或“ aaa 12345xyz” $soFar
,其中包含任何先前匹配的字符串 $result
数组 我不太确定您是否要在字符串中保留“ foo”和“ bar”,因此我只保留了它们。
$str = "whatever foo aaa 12345 bar aaa 34567 aaa 56789 baz fez";
preg_replace_callback(
'/.*?\baaa +\d{5}\b\s*/',
function ($matches) use (&$result, &$soFar) {
$soFar .= $matches[0];
$result[] = trim($soFar);
}, $str
);
print_r($result);
输出:
Array
(
[0] => whatever foo aaa 12345
[1] => whatever foo aaa 12345 bar aaa 34567
[2] => whatever foo aaa 12345 bar aaa 34567 aaa 56789
)
使用preg_match_all和array_map的两步版本:
preg_match_all('/.*?\baaa +\d{5}\b\s*/', $str, $matches);
$matches = array_map(
function ($match) use (&$soFar) {
$soFar .= $match;
return trim($soFar);
},
$matches[0]
);
print_r($matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.