What is the difference between using str_replace and preg_replace in PHP for character replacement?
When replacing characters in a string in PHP, the main difference between str_replace and preg_replace is that str_replace performs a simple text replacement based on exact matches, while preg_replace allows for more advanced pattern matching using regular expressions. If you need to replace a specific character or substring with another one, str_replace is sufficient. However, if you need to replace based on a pattern or multiple criteria, preg_replace is more suitable.
// Using str_replace to replace a character in a string
$string = "Hello, world!";
$new_string = str_replace(",", "!", $string);
echo $new_string;
// Using preg_replace to replace based on a pattern
$string = "The quick brown fox jumps over the lazy dog.";
$new_string = preg_replace("/\b[A-Za-z]{4}\b/", "****", $string);
echo $new_string;