PHP – str_replace (replace characters in a string)

The function str_replace() (as defined in PHP manual) – “replace all occurrences of the search string with the replacement string.

What this means if you simply need to replace a character in a variable or a word in a phrase you should use this function. (If you need to use regular expressions to find a pattern match then use preg_replace() instead).

$text = 'I like apples.';
$new_text = str_replace('like', 'hate', $text);
echo $new_text; // will print 'I hate apples.'

As simple as that.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>