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 add commas easily to a string of numbers?How do I make the first letter of each word upper case?
Hello, Is it possible to specify a character-encoding in the filter_var function. Thank you for your reply, Jan
How do I find the ASCII value of a string character?
How do I display newline characters on a webpage?
