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:
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:
1 2 3 4 5 6 7 |
<?php // Declare String variable $myStr = "Learn with examples"; //Replace string characters number of words in a string echo str_replace("examples", "TutorialDeep!", $myStr); ?> |
Output
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:
1 2 3 4 5 6 7 |
<?php // Declare String variable $myStr = "Learn with examples"; //Replace string characters number of words in a string echo substr_replace($myStr, "PHP with TutorialDeep!", 6); ?> |
Output
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:
1 2 3 4 5 6 7 8 |
<?php // Declare String variable $myStr = "This is your string."; //Replace string characters from specified position $result = preg_replace('/your/','my',$myString); echo $result; ?> |
Output
The output shows the string with the replaced content.
You May Also Like to Read