How do I do to change the first occurrence of a word in a string?
Example:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
to
$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This works, although a bit inefficient:
The other popular answer:
does not work. The fourth argument of
str_replaceshould be a variable, which is passed by reference andstr_replacewill set it to the number of replacements made.A better solution would be to extract two sub-strings from the input string:
Hello, call it$s1Hello, call it$s2One can use the
strposto get the position.Result is
$s1.'Welcome'.$s2