What is the issue with using str_replace function in PHP to replace characters in a string?

The issue with using the str_replace function in PHP to replace characters in a string is that it replaces all occurrences of the specified substring, which may not be the desired behavior. To solve this issue and replace only the first occurrence of the substring, you can use the preg_replace function with a limit parameter set to 1.

// Original string
$string = "Hello, world! Hello, universe!";

// Replace only the first occurrence of "Hello" with "Hi"
$pattern = '/Hello/';
$replacement = 'Hi';
$fixed_string = preg_replace($pattern, $replacement, $string, 1);

// Output the fixed string
echo $fixed_string;