Share this page on Facebook Share this page with your Twitter followers


Updated 13 Nov 2015

How to replace or remove characters using php using str_replace() function


OK - So let's assume you have a sentence or string of text & you need to get rid of some characters, or swap then for different ones - for the sake of this article I have created a string about fruit below:
My string of text:
There are lots of different type of fruit, some examples of fruit are apples, bananas, grapes and lemons.
Now lets imagine this text is pulled from a database somewhere and you need to change the word 'lemons' to oranges every time it's displayed on the page - here's how you do it.
We'll be using a function called str_replace() and in the box below you'll see the code needed to do the switch:
Here's how it will look:
There are lots of different type of fruit, some examples of fruit are apples, bananas, grapes and oranges.
Things to note:
Here is the function broken down below - the first part where it says 'lemons' is the word you will be replacing, the second part where it says 'oranges' is what you will be putting there to replace 'lemons' and the third part where it says '$mystring' is the sentence or phrase you are using as your source:
$output=str_replace("lemons", "oranges", "$mystring");
If you'd like us to give you a quote on any new features or functionality for your site now you can click here