What are the potential pitfalls of using str_replace for keyword replacement in PHP scripts?

Using str_replace for keyword replacement in PHP scripts can lead to unintended replacements if the keyword appears within other words or phrases. To avoid this issue, you can use regular expressions with word boundaries (\b) to ensure that only whole words are replaced.

// Ensure only whole words are replaced using regular expressions with word boundaries
$text = "The quick brown fox jumps over the lazy dog";
$keyword = "fox";
$replacement = "cat";

$pattern = '/\b' . $keyword . '\b/';
$new_text = preg_replace($pattern, $replacement, $text);

echo $new_text;