PHP String Replace

by Vincy. Last modified on July 9th, 2022.

We have already seen many PHP string functions with this blog, like implode/explode, string extract, split and etc. But, it is a never-ending process of learning about PHP Strings and Arrays.

Since that much volume of PHP core functions is there in this area. Not only in volume, these functions have gained that much popularity also.

Again, we are going to deal with one more PHP string functionality replacing the required string in a given context. str_replace() is the most widely used function in PHP for string replace.

This will search for the given string in the context given as well, and replace it with another string which is also provided with this function for replacement.

PHP str_replace()

This function accepts four of the following list of parameters.

  1. $string_search – This parameter contains the string value to be searched.
  2. $string_replace – It contains another string used for the replacement of $string_search.
  3. $context – This is the one subject to what, the string search and replace will take place.
  4. $count – This is an optional parameter. And, this will be set with the count of the number of replacements made with str_replace() invoke.

Note:

  • The fourth parameter specified as the $count in the above list should be a variable reference. Anything other than that will cause the following error.
    Fatal error: Only variables can be passed by reference in ... on line 
    
  • The first three mandatory parameters of PHP str_replace will accept data mixed data types, for example, it can also be an array, instead of a string.

Simple Example for PHP str_replace

First, let us have a simple example for this PHP function by only dealing with string data without any mixed type instead. For that, the following PHP program invokes this function by sending all of its parameters, including the optional count parameter to store the number of replacements made with str_replace().

And, we can see that all such parameters are having string data except the fourth one specified as a variable reference.

<?php
$orginal_string = "Welcome to PHP Blog";
echo "<PRE>";
echo "<b>Original Context: </b>";
echo $orginal_string;
$replaced_array = str_replace(" ", "<br>", $orginal_string, $count);
echo "<p><b>Context After String Replace:</b>";
echo $replaced_array;
echo "<p><b>Number of Replacement: </b>" . $count . "</p>";
?>

In the above program, we are searching for white spaces of the given string context to replace them with line breaks. Since, we have added HTML <BR> tags, these breaks will be reflected in the browser output, as like as,

Original Context: Welcome to PHP Blog
Context After String Replace:
Welcome
to
PHP
Blog
Number of Replacement: 3

In the original context, we can find three white spaces to be replaced with the given replacement string. And, this count is added to the $count variable specified as the fourth parameter of str_replace() and displayed to the browser by using the echo statement.

str_replace with PHP Arrays

Now, we are going to see how str_replace will work with PHP arrays. The following PHP program contains a master array instead of the string context specified for the above example, subject to what the search string will be replaced.

<?php
$orginal_array = array(
    "Welcome to the Blog",
    "the string functions"
);
echo "<PRE>";
echo "<b>Original Array: </b>";
print_r($orginal_array);
$replaced_array = str_replace("the", "PHP", $orginal_array, $count);
echo "<p><b>Array after String Replace with Each Entry:</b>";
print_r($replaced_array);
echo "<p><b>Number of Replacement: </b>" . $count . "</p>";
?>

There are two elements in the master array, and each of these elements will be searched for the string and replaced with PHP. Since there are two occurrences of the search_string, the count will be set to this number.

And then, the output of the program will be as follows.

Original Array: 
Array
(
    [0] => Welcome to the Blog
    [1] => the string functions
)
Array after String Replace with Each Entry:
Array
(
    [0] => Welcome to PHP Blog
    [1] => PHP string functions
)
Number of Replacement: 2

str_replace with Arrays for All Parameters

Similarly, we can apply array data for all of the str_replace parameters. let us have another PHP example for that.

<?php
$orginal_array = array(
    "Welcome to the Blog",
    "the string functions"
);
$search_array = array(
    " ",
    "the"
);
$replace_array = array(
    "<br/>",
    "PHP"
);
echo "<PRE>";
echo "<b>Original Array: </b><br/>";
print_r($orginal_array);
$replaced_new_array = str_replace($search_array, $replace_array, $orginal_array, $count);
echo "<p><b>Array after String Replace with Each Entry:</b><br/>";
print_r($replaced_new_array);
echo "<p><b>Number of Replacement: </b>" . $count . "</p>";
?>

Each of the search array elements is replaced with the replacement array element. And, the output is shown below with the number of replacements that took place.

Original Array: 
Array
(
    [0] => Welcome to the Blog
    [1] => the string functions
)
Array after String Replace with Each Entry:
Array
(
    [0] => Welcome
to
PHP
Blog
    [1] => PHP
string
functions
)
Number of Replacement: 7

Note:

While using array data, replacement behavior will be changed with the mismatch of the array length, if any.

If the search array length is less than the replacement array length, then the replacement will be skipped for that particular replacement array entry that doesn’t have a corresponding search entry. For example,

$search_array = array(" ");
$replace_array = array("
", "PHP");

Since there is only one element in the search array, str_replace will search the master array for this element and replace it with the first entry of the replacement array. And will skip the replacement with the second entry of $replace_array, PHP.

On the other hand, if the $replace_array length is less than $search_array, then the search entry which doesn’t have a corresponding replacement entry will be replaced with an empty string. For example,

$search_array = array(" ","the");
$replace_array = array("<br/>");

In this example, white spaces are replaced with HTML line breaks and the string “the” is replaced with an empty string since there is no entry specified for $replace_array.

Download PHP String Replace Source Code

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page