Phpworker
answered Apr 25 '23 00:00
If you want to replace only the first occurrence of a substring in a string, you can use the str_replace function with a fourth parameter that specifies the number of replacements to be made. Here's an example:
$string = 'The quick brown fox jumps over the lazy dog';
$substring = 'o';
$new_string = str_replace($substring, '0', $string, 1);
echo $new_string; // Outputs: The quick br0wn fox jumps over the lazy dog
In this example, str_replace is used to replace the first occurrence of the letter 'o' with a '0' in the given string. The fourth parameter (1) limits the number of replacements to one. If you omit this parameter or set it to null, str_replace will replace all occurrences of the substring in the string.