您可能希望根据先前的模式匹配返回匹配组:
$word = '[a-z]+';
$sep = '[, ]+';
$words = $captures("~($word)(?:{$sep})?~");
$of = $captures("~xxx ({$word}(?:{$sep}{$word})*) xxx~");
print_r($words($of($subject)));
输出:
Array
(
[0] => red
[1] => blue
[2] => pink
[3] => purple
)
而$captures
一个返回预配置preg_match_all
调用的函数不仅允许处理作为主题的字符串,而且foreach
可以处理任何东西:
$captures = function ($pattern, $group = 1) {
return function ($subject) use ($pattern, $group) {
if (is_string($subject)) {
$subject = (array)$subject;
}
$captures = [];
foreach ($subject as $step) {
preg_match_all($pattern, $step, $matches);
$captures = array_merge($captures, $matches[$group]);
}
return $captures;
};
};
默认情况下,如上例中所用,它返回第一组 (1),但这可以配置。
这允许首先匹配外部模式 ( $of
),然后在每个匹配内部模式 ( $words
) 上。完整示例:
$subject = '/xxx red, blue, pink, purple xxx/';
$captures = function ($pattern, $group = 1) {
return function ($subject) use ($pattern, $group) {
if (is_string($subject)) {
$subject = (array)$subject;
}
$captures = [];
foreach ($subject as $step) {
preg_match_all($pattern, $step, $matches);
$captures = array_merge($captures, $matches[$group]);
}
return $captures;
};
};
$word = '[a-z]+';
$sep = '[, ]+';
$seq = "";
$words = $captures("~($word)(?:{$sep})?~");
$of = $captures("~xxx ({$word}(?:{$sep}{$word})*) xxx~");
print_r($words($of($subject)));
见现场演示。