How to replace particular characters of a string in PHP?

In this tutorial, we are going to see how to replace particular characters in PHP. To better understand what are we going to learn let’s see an example.

In this tutorial we take a string for the understanding purpose:

My pen is red and your beg is also red

Now suppose we want to replace both the “pen” and “beg” into another one “book”. So after replacing the string, it will look like:

My book is red and your book is also red

In PHP there is a function called str_replace() function which can replace any character or characters of a string with any characters that you want. Below is the syntax of this PHP function:


Now suppose we want to replace “pen” and “beg” with “book”. Below is the PHP code which performs this task:

  $substance = "My pen is red and your beg is also red";
  $new_substance = str_replace(array('pen','beg'), "book", $substance);
  echo $new_substance;

Well, in the above PHP code, we can see that we have passed those characters are sent to the str_replace function as an array. So here the first parameter is an array. The array defined which character of the string needs to be replaced.

How to validate phone number in PHP?

Create PHP function with optional parameter or argument

Now, if we see the output of the above program, it will show:

My book is red and your book is also red

If you want to replace only one character set of a string then there is no need to pass an array. Suppose you just want to replace the pen to book. In this case below is the PHP code:

str_replace(array('pen', "book", $substance);


Leave a Reply

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