Reputation: 1146
my text:
bob have message123 and alice has message
i want:
bob have newmessage and alice has newmessage
My current code is:
$fullText= str_replace("message123", "newmessage", $fulltext);
$fullText= str_replace("message", "newmessage", $fulltext);
but it becomes:
bob have newnewmessage and alice has newmessage
Upvotes: 1
Views: 1148
Reputation: 1
Use the strtr() function -- it will not pass again over stuff that it already replaced:
$fullText = 'bob have message1 and alice has message without 1.';
$fullText = strtr( $fullText, array(
"message1" => "newmessage",
"message" => "newmessage" ) );
Upvotes: 0
Reputation: 5151
For the simplest solution, you could just add spaces:
$fullText= str_replace(" message1 ", " newmessage ", $fulltext);
$fullText= str_replace(" message ", " newmessage ", $fulltext);
Or using multiple needles:
$fullText = str_replace(array(' message1 ', ' message '), array(' newmessage ', ' newmessage '), $fullText);
Upvotes: 0
Reputation: 909
You could always use preg_replace.
In this case:
$fullText=preg_replace("/\bmessage[0-9]*/", "newmessage", $fullText);
which will replace message, message1, message2 etc.
Upvotes: 1