PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I replace a word in a string in PHP?


Manipulating strings and data is what the majority of PHP is about and what you will find yourself doing most - particularly if you use PHP on the web to process and manipulate user data entered into forms, for instance.

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.



More strings PHP Questions

What is the difference between join and implode in PHP?
How do I convert newlines to HTML line break tags?
How do I count the number of words in my text?
How do I find the position of a letter in a string in PHP?
How do I print the " in an echo statement?