开发者

preg_replace successful or not

Is there any way to tell if a preg_replace was successful or not?

I tried:

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

?>

and yes, I looked at php docs for this one. Sorry about my stupid questions earlier.


You can use the last param of preg_replace: &$count, which will contain the number of replacements that were done:

$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.";

edited to fix the issue when there are two of the same in $patterns


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


From the documentation:

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

So:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜