How to Replace String in PHP

Minahil Noor Feb 02, 2024
How to Replace String in PHP

This article will introduce a method to replace part of a string in PHP.

Use the str_replace() Function to Replace Part of a String in PHP

In PHP, the specialized function to replace a part of a string is str_replace(). This function searches the given substring and replaces it with the provided value. The correct syntax to use this function is as follows.

str_replace($search, $replace, $subject, $count);

The str_replace() function has only four parameters. The details of its parameters are as follows.

Variables Description
$search mandatory It is the string or an array that we want to search in the given string or array. This $search string or array is then replaced by the given $replace parameter.
$replace mandatory It is the string or array that will be placed on the $search position.
$subject mandatory It is the string or array whose substring will be searched and replaced.
$count optional If given, it counts the replacements performed.

This function returns the modified string or array. The program below shows how we can use the str_replace() function to replace part of a string in PHP.

<?php
$mystring = "This is my string.";
echo("This is the string before replacement: ");
echo($mystring);
echo("\n");
$mynewstring = str_replace(" my ", " ", $mystring);
echo("Now, this is the string after replacement: ");
echo($mynewstring);
?>

Output:

This is the string before replacement: This is my string.
Now, this is the string after replacement: This is string.

The function has returned the modified string.

Now, if we pass the $count parameter then it will count the replacements made.

<?php
$mystring = "This is my string.";
echo("This is the string before replacement: ");
echo($mystring);
echo("\n");
$mynewstring = str_replace(" my ", " ", $mystring, $count);
echo("Now, this is the string after replacement: ");
echo($mynewstring);
echo("\n");
echo("The number of replacements is: ");
echo($count);
?>

Output:

This is the string before replacement: This is my string.
Now, this is the string after replacement: This is string.
The number of replacements is: 1

The output shows that the function makes only one replacement. It means that the $search string only appeared one time in the passed string.

Related Article - PHP String