2017-05-25 69 views
0

假設我們有跟隨陣列如何獲得基於字符串順序匹配的字符串模式

$regexList = ['/def/', '/ghi/', '/abc/']; 

波紋管:

$string = ' 

{{abc}} 
{{def}} 
{{ghi}} 

'; 

的想法是要從上到下經過字符串並依靠正則表達式列表,找到結果並用大寫內容替換爲模式爲tha t無論按照什麼順序匹配發生的字符串順序regexListarray是。

所以,這就是我想要的輸出:

  • ABC被匹配:/ ABC /;
  • DEF被匹配:/ def /;
  • GHI匹配:/ ghi /;

或在leats

  • ABC通過模式匹配:2;
  • DEF符合條件:0;
  • GHI匹配:1;

這個代碼我已經嘗試:

$regexList = ['/def/', '/ghi/', '/abc/']; 

$string = ' 

abc 
def 
ghi 

'; 

$string = preg_replace_callback($regexList, function($match){ 
    return strtoupper($match[0]); 
}, $string); 

echo '<pre>'; 
var_dump($string); 

這只是輸出:

string(15) " 

ABC 
DEF 
GHI 

" 

如何才能得到補償或模式匹配在$這些字符串字符串順序(從上到下)?謝謝。

+0

的[獲取在預浸\ _replace \當前指數可能的複製_callback?](https://stackoverflow.com/questions/8484062/getting-the-current-index-in-preg-replace-callback) – RST

+0

@RST:這與問題無關。 – Toto

回答

0

@Barmar是正確的,但我要修改它一點:

$order = []; 

$string = preg_replace_callback('/(def)|(ghi)|(abc)/', function($match) use (&$order) { 
    end($match); 
    $order[key($match)] = current($match); 
    return strtoupper($match[0]); 
}, $string); 

print_r($order); 

輸出:

Array 
(
    [3] => abc 
    [1] => def 
    [2] => ghi 
) 
+0

謝謝!而已! – e200

1

請勿使用正則表達式數組,請使用具有替代方法和捕獲組的單個正則表達式。然後你可以看到哪個捕獲組不是空的。

$regex = '/(def)|(ghi)|(abc)/'; 
$string = preg_replace_callback($regex, function($match) { 
    for ($i = 1; $i < count($match); $i++) { 
     if ($match[$i]) { 
      return strtoupper($match[$i]) . " was matched by pattern " . $i-1; 
     } 
    } 
}, $string); 
+0

您的代碼輸出:串(24) 「 {{1}} {{1}} {{1}} 」 – e200

+0

謝謝!您的代碼可以幫助我獲得解決方案! – e200