What are the potential pitfalls of using str_replace in PHP to replace spaces in a string?

Using str_replace to replace spaces in a string can be problematic because it will replace all instances of spaces, including spaces within words. To avoid this issue, you can use the PHP function preg_replace with a regular expression pattern to only replace spaces that are not within words.

$string = "This is a sample string with spaces";
$pattern = '/\b\s+\b/';
$replacement = '_';
$new_string = preg_replace($pattern, $replacement, $string);

echo $new_string;