如何让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.发布于 2014-12-07 16:22:39
您必须使用look look/ahead零长度断言(而不是通常的模式,该模式使用您要查找的内容周围的字符):http://www.regular-expressions.info/lookaround.html
发布于 2017-04-11 18:00:51
环视断言不会有帮助,原因有两个:
因为它们是零长度的,所以它们不会返回你需要的字符。
这将产生您需要的输出:
<?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";
}
}
?>https://stackoverflow.com/questions/27340905
复制相似问题