Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


The PHP String str_replace() function returns a string which is the replaced version of the specified string. It is used to replace a substring of the given string with another substring. The function has one optional parameter which can be used to specify counts of replacement.

Please not that the str_replace() can also be used to replace substrings from a string array.

Please note that it does not change the original string and only returns the replaced version of the given string.

Syntax

str_replace(find, replace, string, count)

Parameters

find Required. Specify what substring to change.
replace Required. Specify what substring to change into.
string Required. Specify the string to search.
count Optional. Specify a variable that counts number of replacement.

Return Value

Returns a replaced version of the specified string.

Example:

In the below example, every occurrence of "Hello" in MyString is replaced by "Hi" using str_replace() function.

<?php
$MyString = "Hello World, Hello PHP, Hello Programming.";

$NewString = str_replace("Hello", "Hi", $MyString);
echo $NewString."\n";

//i is used to find the count of replacement
$NewString = str_replace("Hello", "Hi", $MyString, $i);
echo "Count of replacement: ".$i;   
?>

The output of the above code will be:

Hi World, Hi PHP, Hi Programming.

Count of replacement: 3

Example:

In the below example, every occurrence of "Hello" in MyArray is replaced by "Hi" using str_replace() function.

<?php
$MyArray = array("Hello", "World", "Hello", "PHP", "Hello", "Programming");

$NewArray = str_replace("Hello", "Hi", $MyArray);
 print_r ($NewArray);

//i is used to find the count of replacement
$NewArray = str_replace("Hello", "Hi", $MyArray, $i);
echo "Count of replacement: ".$i;  
?>

The output of the above code will be:

Array
(
    [0] => Hi
    [1] => World
    [2] => Hi
    [3] => PHP
    [4] => Hi
    [5] => Programming
)

Count of replacement: 3

❮ PHP String functions

5