1

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

  • 'new' is repeated because str_replace(); search whole text and find replace again.
  • is it possible not to replace the text which is already replaced.
1
  • You can also pass array of strings as parameters in str_replace ex: str_replace( array( "message", "newmessage1" ), "newmessage", $fullText ); Commented Sep 15, 2013 at 19:33

3 Answers 3

1

You could always use preg_replace.

In this case:

$fullText=preg_replace("/\bmessage[0-9]*/", "newmessage", $fullText);

which will replace message, message1, message2 etc.

Sign up to request clarification or add additional context in comments.

1 Comment

If you're not familiar with regex: / marks the beginning and end of the search string, \b looks for the beginning of a new word boundary [0-9]* looks for zero or more numbers at the end of the string "message"
0

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);

Comments

0

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" ) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.