How do I replace a word in a string in PHP?
Therefore it is good to know how to replace a specific word or string within a string with something else.
Let's say, for instance, you want to remove swear words from a string of data. To make this example easy and show you how the function works, we're going to turn the word 'bloody' into 'b****y' in our example, so that it can be safely posted, say, on your message board:
<?php
//PHP program to clean swear words from data
$usersays = "I hate this bloody film it's useless!";
$cleaned = str_replace("bloody","b****y",$usersays);
echo "You wrote: $cleaned";
//You wrote: I hate this b****y film it's useless!
?>
If you had a whole list of words you wanted to substitute, then you could simply put them into an array and then loop around replacing each one in the input string.
Comment on this Question and Answer >>>
ASK A QUESTION
More strings PHP Questions
How do I format the output of a string?How do I count how many times each character occurs in a string?
how to compare strings in PHP?
How do I find the position of a letter in a string in PHP?
How do I break email address into username and hostname?
