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:
source share