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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With