2013-09-24 50 views
0

Php.net過這樣的preg_replace片斷如何使用模式是一個數組(PHP)的preg_match

$string = 'The quick brown fox jumped over the lazy dog.'; 
$patterns = array(); 
$patterns[0] = '/quick/'; 
$patterns[1] = '/brown/'; 
$patterns[2] = '/fox/'; 
$replacements = array(); 
$replacements[2] = 'bear'; 
$replacements[1] = 'black'; 
$replacements[0] = 'slow'; 
echo preg_replace($patterns, $replacements, $string); 

有沒有一種方法,以便做這樣的事情

運行$圖案的preg_match

如果preg_match在$ string中找到,那麼preg_replace else回聲沒有匹配找到

謝謝。

回答

1

這是你在哪裏找?

$string = 'The quick brown fox jumped over the lazy dog.'; 
$patterns = array(); 
$patterns[0] = '/quick/'; 
$patterns[1] = '/brown/'; 
$patterns[2] = '/fox/'; 
$replacements = array(); 
$replacements[2] = 'bear'; 
$replacements[1] = 'black'; 
$replacements[0] = 'slow'; 

foreach ($patterns as $pattern) { 
    if (preg_match("/\b$pattern\b/", $string)) { 
    echo preg_replace($pattern, $replacements, $string); 
     } 
} 
+0

試過了更早。不起作用。很確定你可以放棄preg_replace的回聲。無法使用或不使用它。 – stevenmw

+0

編輯我的答案;) –

+0

這仍然不起作用。每個模式需要像'/ quick /'我想盡可能保持我的數組。也許我可以使用implode或foreach? – stevenmw

2

似乎所有你想要做的是有一個preg_replace也提醒您的是沒有發生的比賽?

下面會爲你工作:

$string = 'The quick brown fox jumped over the lazy dog.'; 
$patterns = array(); 
$patterns[0] = '/quick/'; 
$patterns[1] = '/brown/'; 
$patterns[2] = '/pig/'; 
$replacements = array(); 
$replacements[2] = 'bear'; 
$replacements[1] = 'black'; 
$replacements[0] = 'slow'; 

for($i=0;$i<count($patterns);$i++){ 
    if(preg_match($patterns[$i], $string)) 
     $string = preg_replace($patterns[$i], $replacements[$i], $string); 
    else 
     echo "FALSE: ", $patterns[$i], "\n"; 
} 
echo "<br />", $string; 

/** 

Output: 

FALSE: /pig/ 
The slow black fox jumped over the lazy dog. 
*/ 

$string = preg_replace($patterns, $replacements, $string, -1, $count); 
if(empty($count)){ 
    echo "No matches found"; 
} 
+0

也不起作用。 – stevenmw

+0

它確實有效。我已經測試了它並顯示了輸出結果。您正在使用的實際輸入和模式/替換陣列是什麼? – Steven

+0

它在某種意義上起作用。整個過程是用$替換中的字符串替換$ patterns中的字符串。您的代碼會按原樣回顯$ string而不會替換任何內容。例如原來的代碼輸出,「熊黑慢慢跳過懶狗。」它從$ patterns數組中替換任何找到的字符串,並用$ replacements中的相應單詞替換它們。 – stevenmw