How to replace string in PHP
Last Updated on Dec 16, 2022 - Written By Torikul Islam
String is a collection of characters. You can replace string using str_replace() function. It is a PHP built in function.
In this article, I’m going to replace a string with another by using the PHP built-in str_replace() function. I putted here some useful examples and brief discussion.
Syntax:
str_replace(substring, replaced_string, original_string);
We need to provide three parameters.
Sub-string: substring is the string present in the original string that should be replaced
Replaced string: replaced_string is the new string that replaces the substring.
Original_string: original_string is the input string.
Count: This is an optional parameter to show the number of replacements
You can use PHP variable in the placement of parameters.
Example and discussion: Replace string in PHP
The examples below showing different application to make string replacement.
Example 1: Replaces a string with another string
<?php
//input string
$string = "I like coffee.";
//replacing string
$replace = str_replace("coffee","tea",$string);
//showing result
echo $replace;
?>
Output:
I like tea.
Example 2: Replace string with empty string
<?php
//input string
$string = "I like coffee.";
//replacing string
$replace = str_replace("coffee","",$string);
//showing result
echo $replace;
?>
Output:
I like .
Example 3: Replace string with integer
<?php
//input string
$string = "I like coffee.";
//replacing string
$replace = str_replace("coffee","2",$string);
//showing result
echo $replace;
?>
Output:
I like 2.
Note: This function is case-sensitive. You can use the str_ireplace() function to perform a case-insensitive search.
Example 5: Case insensetive replacement
<?php
echo str_replace("coffee","tea","I like Coffee.");
?>
This will result no replacement due to case sensitiveness. You need to follow the code below instead.
<?php
echo str_ireplace("coffee","tea","I like Coffee.");
?>
This will replace the string.
Example 6: Replace multiple words using array
<?php
//input string
$str = "I like pink, blue, and red colour";
//words to replace
$arr = array("blue","red","green","yellow");
//after replacing the words
$new = array("blue1","red1","green1","yellow1");
//replacing multiple words
$replace = str_replace($arr,$new,$str,$i);
//showing result
echo $replace.'<br>';
//showing the number of occurences
echo 'Total replacement '.$i;?>
Output:
I like pink, blue1, and red1 colour
Total replacement 2