Replace A Character Of String Using PHP With Other Character
In this post, I am going to discuss a thing which may be interesting to you.
Suppose you have a text block which represents as a string in PHP and you want to replace a particular text or character with a new character. Well, it is very easy to do it because there is an inbuilt function in PHP which can do this task.
About str_replace() PHP function
The str_replace() function is an inbuilt function of PHP which can be used to replace some characters with some other characters in a string.
Below is a simple example of a PHP str_replace() function which replaces the text user_name into Raju:
<?php echo str_replace("user_name","Raju","Hello user_name!"); ?>
It will show the output “Hello Raju!” instead of showing “Hello user_name!”. You can also pass the replacing character as a variable like you can see below:
<?php $username = "Raju"; echo str_replace("user_name", $username, "Hello user_name!"); ?>
It will return the same output “Hello Raju!”.
Using str_replace() PHP function with array
Below is another example code of using the str_replace function on an array from w3schools:
<?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "<br>" . "Replacements: $i"; ?>
It will return the output like below:
Array (  => blue  => pink  => green  => yellow )
So you can see that str_replace also can be used in an array and it also returns an array by replacing the value.
Below are some rules of using PHP str_replace () function:
- str_replace function in PHP is case-sensitive function.
- If the string to be found by this function is an array, it returns an array too
- If both the character to find and replace are arrays, and replace has fewer elements than it found, an empty string will be used as replace
- If the string to be searched is an array, find and replace is performed with every array element
- If it find is an array and replace is a string, the replace string will be used for every find value in the array