Preg_replace successful or not

Is there a way to find out if 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. Forgive my stupid questions before.

+4
source share
3 answers

You can use the last parameter preg_replace: &$count , which will contain the number of replacements made:

 $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 problem if in $patterns

there are two identical words:
+4
source
 if (preg_replace($patterns, '<b>$0</b>', $stringz, 1) != $stringz) echo 'preg_replace was successful' 
+5
source

From the documentation :

If matches are found, the new object will be returned, otherwise it will be returned unchanged or NULL if an error occurs.

So:

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

All Articles