preg_replace成功与否

时间:2010-11-23 01:57:01

标签: php

有没有办法判断preg_replace是否成功?

我试过了:

<?php

$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/", "/red/");

if ($string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1)) {
echo "<textarea rows='30' cols='100'>$string</textarea>";
}else{
    echo "Nope. You didn't have all the required patterns in the array.";
    }

?>

是的,我查看了这个文档的php文档。对于我之前的愚蠢问题感到抱歉。

3 个答案:

答案 0 :(得分:5)

if (preg_replace($patterns, '<b>$0</b>', $stringz, 1) != $stringz)
   echo 'preg_replace was successful'

答案 1 :(得分:4)

您可以使用preg_replace的最后一个参数:&$count,其中包含已完成的替换次数:

$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/","/green/");
$new_patterns = array();
foreach ($patterns as $p)
    if (array_key_exists($p, $new_patterns))
      $new_patterns[$p]++;
    else
      $new_patterns[$p] = 1;
$string = $stringz;
$success = TRUE;
foreach ($new_patterns as $p => $limit)
{
  $string = preg_replace($p, '<b>\\0</b>', $string, $limit, $count);
  if (!$count)
  {
    $success = FALSE;
    break;
  }
}
if ($success)
  echo "<textarea rows='30' cols='100'>$string</textarea>";
else
  echo "Nope. You didn't have all the required patterns in the array.";

修改以解决$patterns

中有两个相同的问题

答案 2 :(得分:2)

来自documentation

  

如果找到匹配项,则为新主题   将被退回,否则将被录取   将返回不变或NULL   发生错误。

所以:

$string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1);
if($string != $stringz) {
    // something was replaced
}