2014-12-07 43 views
0

如何讓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

瞭解了非貪婪匹配 – hoijui 2014-12-07 08:19:33

+0

你希望的,因爲一場比賽被包括在另外你不能得到結果。使用lookahead和lookbehind斷言,但在PHP中,後視將不允許內部的量詞。 – 2014-12-07 08:26:51

回答

0

環視斷言不會幫助,原因有二:

  • 因爲它們是零長度,他們不會返回您需要的字符。
  • 正如Avinash Raj指出的那樣,PHP lookbehind不允許*

這就產生了你所需要的輸出:

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

?>