How Do I Replace Characters in String Using PHP

Last Updated on May 13, 2021 by Roshan Parihar

In this tutorial, learn how to replace characters in string using PHP. The short answer is to use the str_replace() and specify the characters to replace with.

You can also use the substr_replace() that replaces the characters from the specified position. Let’s find out with the examples given below.

Method 1: How to Replace Characters in String Using str_replace() in PHP

The syntax of str_replace() is as given below:

str_replace(find, replace, string, count)

find argument requires content to find in the string, replace argument is the new content to replace with the old content, string argument is the string variable, the count is an optional argument to specify the number of replaced characters.

Now, you have an idea of using the function. So, let’s use it to replace the characters as given in the example below:

Output

Learn with TutorialDeep!

The above replaces the string ‘example’ with the new string content ‘TutorialDeep!’. You can specify more characters to change with the existing content.

Method 2: Using substr_replace() to Replace String Characters From the Specified Position

You can replace the characters in string from the specified position using the substr_replace(). The function takes three arguments in which the first argument takes the string variable, the second is the new content to replace, third is the position from where you have to replace the content. Let’s see with the example given below:

Output

Learn PHP with TutorialDeep!

The above example replaces the characters from the 6th position in the given string.

Method 3: Using preg_replace() in PHP

In addition to the above examples, you can also replace the string characters using the preg_replace(). The function takes three arguments in which the first argument is the content of string within backslash (\), second is the new character to replace with the old, third is the given string variable or string. You can check the example given below to learn the method:

Output

This is my string.

The output shows the string with the replaced content.

You May Also Like to Read

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.