Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace successful or not

Tags:

php

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.

like image 283
test Avatar asked Nov 23 '10 01:11

test


1 Answers

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

like image 117
cambraca Avatar answered Oct 01 '22 16:10

cambraca