8 Examples of PHP str_replace Function to Replace Strings

Image representing PHP's str_replace Function

The str_replace function

  • The str_replace function of PHP is used to replace a string with the replacement string.
  • PHP str_replace function is case-sensitive.
  • If you want to perform case-insensitive replacements then use the str_ireplace function (see the last example in this tutorial).
  • First, have a look at the str_replace syntax and examples below.

Syntax of using the str_replace function

This is how you may use the str_replace function:

 str_replace(search_string,replace_with,$source_string,$count)

Where:

Parameter Description
search_string
  • The search_string is the string you want to search in the source string to be replaced.
  • It is also called a needle.
  • You may use arrays to specify multiple search strings or needles.
replace_with The replace_with is the string you want to replace with a searched string. There, you may also use arrays for specifying multiple terms.
$source_string The $source_string is the string you want to perform an action.
$count The $count is an optional parameter that if you pass, it will be set to the total replacements done.

Note that, it does not limit the number of replacements.

An example of using the PHP str_replace function

In this example, a simple string is created which is assigned to a variable. The string is:

$str_rep = “A tutorial for learning str_replace function in PHP!”;

After that, the str_replace function is used to replace the word “str_replace” with “String replacement”.

This is how it is done:

<?php

$str_rep = "A tutorial for learning str_replace function in PHP!";

echo str_replace("str_replace","String replacement",$str_rep);

?>

Output:

A tutorial for learning String replacement function in PHP!

An example of using the HTML tag to highlight replacements

  • In this example, a string is created where the word “is” is used three times.
  • In the str_replace function, an HTML <span> tag is added with background color in <style> section, so the replaced words will be highlighted after executing the string replace function.
  • See the example online by clicking the link below:

PHP replace HTML

Online demo and code

This is how the string replacement is done:

<?php

$src_rep = ("That is A test sentence for str_replace. </br>That is A test sentence for str_replace. </br>That is A test sentence for str_replace.");

$count = 1;

echo str_replace("is","<span>was</span>",$src_rep,$count);

?>

You can see the complete code including markup and CSS in the demo page.

An example of using count to get total replacements

In certain scenarios, it may be useful to get how many replacements are done by using the str_replace function.

In this example, I am using the same code as above, except, passing a variable to get the total count of the replacements.

The last line in the output will show the number:

The code:

<!doctype html>
<html>

<head>

<style>
.divcls {
  background: #400000;
  height: auto;
  width:290px;
  border-radius: 15px;
  padding:20px;
  font-size:17px;
  color:#fff;   
}
span{
    background: #FA4238;
}
</style>
 

  
</head>
<body>
<div class="divcls"><h3> A demo of string replace in PHP:</h3><br /><br />
< ?php
$src_rep = ("That is A test sentence for str_replace. </br>That is A test sentence for str_replace. </br>That is A test sentence for str_replace.<BR><BR><BR>");
echo str_replace("is","<span>was</span>",$src_rep,$count);
echo "Total number of replacements = " .$count;
?>
</div>
</body>
</html>

Output:

PHP replace count

This is how the count parameter is used in the function:

echo str_replace(“is”,”<span>was</span>”,$src_rep,$count);

This got the value of total replacements after the PHP string replace function is executed. The $count value is displayed by using the echo statement, which is 3.

Specifying an array as needle to replace a string

  • In some situations, you may need to specify two or more different search terms or needles to replace the target string.
  • You may do that by using an array in str_replace function.
  • In this example, an array of two elements is created.
  • The array is used in the string replace method as search string or needle:

PHP str_replace

Online demo and code

This is how the array was created and used in the function:

$arr_repl = array("This", "function");



$source_string= "This is a replace string tutorial by using str_replace function.";

$str_replaced = str_replace($arr_repl, "that", $source_string);

You see, two words “This” and “function” are replaced by “that” in the target string. However, this is not logical to replace “function” with “that”. It should have its own word to be replaced with.

You may do it by using another array in the replacement_string as shown in the example below.

A demo of using search and replacement arrays in str_replace function

Just extend the above example by creating another array of two elements. This array contains the replacement terms. See the example below:

<!doctype html>
<html>

<head>

<style>
.divcls {
  background: #004000;
  height: auto;
  width:290px;
  border-radius: 15px;
  padding:20px;
  font-size:17px;
  color:#fff;   
}
span{
    background: #FA4238;
}
</style>
 

  
</head>
<body>
<div class="divcls"><h3> A demo of string replace in PHP</h3><br /><br />
< ?php
$arr_needle = array("This", "function");
$arr_replace = array("That", "method");
$source_string= "This is a replace string tutorial by using str_replace function.";
$str_replaced = str_replace($arr_needle, $arr_replace, $source_string);

echo "The source string: <BR>" .$source_string ."<BR><BR><BR>";
echo "The replaced string: <BR>" .$str_replaced;
?>
</div>
</body>
</html>

Output:

PHP str_replace arrays

You see, the first array, which specifies the search terms in the given string is replaced by the second array elements that are specified in the “replacement string” parameter.

PHP’s str_replace is a case-sensitive function?

As mentioned earlier, the PHP str_replace is a case-sensitive function. So “This” has different meanings than “this” while performing replacement by using the str_replace function.

See the following example:

PHP str_replace case sensitive

Online demo and code

In the source string, the word “test” is used with different cases. In the str_replace function, the word “Test” is searched, and “TEST” is given as the replacement term:

$str_replaced = str_replace(“Test”, “<span>TEST</span>”, $source_string);

You can see that the output is the replacement string where only “Test” occurrence is modified. The word “test” did not change.

Performing case-insensitive replacement by using str_ireplace function

The answer to perform case-insensitive replacement is using the PHP str_ireplace function. The syntax of using the str_ireplace function is just like the str_replace function.

The only difference is the str_ireplace is the case-insensitive version of the str_replace function.

Using the same example as above with str_ireplace function, see the output:

PHP str_ireplace

Online demo and code

This is how the str_ireplace is used:

$source_string = ("This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. </br>This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters.");


$str_replaced = str_ireplace("Test", "<span>TEST</span>", $source_string);


echo "The source string: <BR>" .$source_string ."<BR><BR><BR>";

echo "The replaced string: <BR>" .$str_replaced;

In the output, you can see that all occurrences of the word “test” are replaced by “TEST”.

An example of user selected values from HTML dropdowns

In this example, two HTML dropdowns are created with pre-defined values. The first is for selecting the search term or needle in the target string. The other is for choosing the replacement term in the destinated string.

After selecting two related values e.g.

Search term / needle = function

Replacement term = method

Press the button to execute the str_replace function of PHP. The values will be submitted by using the “post” method in <form> tag and will be assigned to variables by using $_POST associative array.

The str_replace function will execute and perform the replacement as shown in the example below:

PHP str_replace user values

Online demo and code

You see, the source and replaced strings are shown in the paragraph tags. This is how the markup and PHP code is used in the example.

The markup for the <form> tag:

<form method="post" target="">

<div class="divcls"><p>A demo with user selected terms</p>

<p><label>Replace Term: </label><select name="searchstr">

<option value="targetted">targetted</option>

<option value="search term">search term</option>

<option value="function">function</option>

</select>

</p>

<p>

<label>To be Replaced with: </label><select name="replacestr">

<option value="destinated">destinated</option>

<option value="needle">needle</option>

<option value="method">method</option>

</select>

</p>



<p><input type="submit" class="btncls" value="Execute str_replace function"></p>



</div>

<p class="srcstring"><strong>The source string<br /><br /></strong>

The str_replace method is used to perform replacement in targetted string by the given search term.<br> The str_replace is case-sensitive function.

</p>



</div>

</form>

The PHP code to execute the str_replace function:

$search_string=$_POST["searchstr"];

$replace_string=$_POST["replacestr"];

$source_string = ("The str_replace method is used to perform replacement in targetted string by the given search term.<br> The str_replace is case-sensitive function.");



if ($search_string != ""){

$str_replaced = str_ireplace($search_string, "<span>" .$replace_string ."</span>", $source_string);



// echo "The source string: <BR>" .$source_string ."<BR><BR><BR>";

echo "<p class='replaced_string'><strong>The replaced string: <br /><br /></strong>" .$str_replaced . "</p>";

}

Similarly, you may use textboxes or dropdowns with larger lists in some other way to allow users to replace specific terms if you ever come across this type of scenario.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!