2013-09-24 51 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