Skip to content
PHP Logo

What is the potential issue with using str_replace in the given PHP code snippet?

Using str_replace in the given PHP code snippet may result in unintended replacements. This is because str_replace will replace all occurrences of the search string in the input string. To address this issue, you can use preg_replace with a regular expression pattern to replace only the exact word.

php
// Given PHP code snippet
$input = "The quick brown fox jumps over the lazy dog";
$output = str_replace("fox", "cat", $input);
echo $output; // Output: "The quick brown cat jumps over the lazy dog"

// Fixed PHP code snippet using preg_replace
$input = "The quick brown fox jumps over the lazy dog";
$output = preg_replace("/\bfox\b/", "cat", $input);
echo $output; // Output: "The quick brown cat jumps over the lazy dog"