如何使preg找到正则表达式模式的所有可能解决方案?
以下是代码:
<?php
$text = 'Amazing analyzing.';
$regexp = '/(^|\\b)([\\S]*)(a)([\\S]*)(\\b|$)/ui';
$matches = array();
if (preg_match_all($regexp, $text, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
echo "{$match[2]}[{$match[3]}]{$match[4]}\n";
}
}
?>
输出:
Am[a]zing
an[a]lyzing.
我需要的输出:
[A]mazing
Am[a]zing
[A]nalyzing.
an[a]lyzing.
答案 0 :(得分:0)
你必须使用后面/后面的零长度断言(而不是正常模式,它消耗你正在寻找的字符):http://www.regular-expressions.info/lookaround.html
答案 1 :(得分:0)
Lookaround断言不会有所帮助,原因有两个:
*
。这会产生您需要的输出:
<?php
$text = 'Amazing analyzing.';
foreach (preg_split('/\s+/', $text) as $word)
{
$matches = preg_split('/(a)/i', $word, 0, PREG_SPLIT_DELIM_CAPTURE);
for ($match = 1; $match < count($matches); $match += 2)
{
$prefix = join(array_slice($matches, 0, $match));
$suffix = join(array_slice($matches, $match+1));
echo "{$prefix}[{$matches[$match]}]{$suffix}\n";
}
}
?>