What is the difference between using str_ireplace and preg_replace_callback to replace and number duplicate strings in PHP?
When we want to replace and number duplicate strings in PHP, we can use either str_ireplace or preg_replace_callback. The main difference between the two is that str_ireplace is a simpler function that performs a case-insensitive search and replace, while preg_replace_callback allows for more complex pattern matching using regular expressions and a callback function to handle the replacement logic.
// Using str_ireplace to replace and number duplicate strings
$string = "apple, banana, apple, orange, banana";
$replace = "fruit";
$count = 0;
$new_string = str_ireplace("apple", $replace . ++$count, $string, $count);
echo $new_string;
// Using preg_replace_callback to replace and number duplicate strings
$string = "apple, banana, apple, orange, banana";
$count = 0;
$new_string = preg_replace_callback('/\b(\w+)\b/', function($matches) use (&$count) {
static $replacements = [];
$word = $matches[1];
if (!isset($replacements[$word])) {
$replacements[$word] = $word;
} else {
$replacements[$word] .= ++$count;
}
return $replacements[$word];
}, $string);
echo $new_string;