尽可能检查模式

时间:2014-12-07 08:16:21

标签: php regex

如何使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.

2 个答案:

答案 0 :(得分:0)

你必须使用后面/后面的零长度断言(而不是正常模式,它消耗你正在寻找的字符):http://www.regular-expressions.info/lookaround.html

答案 1 :(得分:0)

Lookaround断言不会有所帮助,原因有两个:

  • 由于它们是零长度,因此不会返回您需要的字符。
  • 正如Avinash Raj所指出的那样,PHP背后隐藏并不允许*

这会产生您需要的输出:

<?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";
    }
}

?>