PHP str_replace: Main Tips
- By using this function, you can replace characters in a text string.
- PHP
str_replace
is case-sensitive. If you need to perform a case-insensitive search, trystr_ireplace()
function. - If the variable specified by the third argument is an array, the function will check every array element and will return an array.
- If the first and second function arguments are both arrays, and the second argument has fewer elements than the first, an empty string will be used as a replacement.
- If the first argument is an array and the second is a string, the string will be used for every array element.
Function Explained
By using the str_replace
PHP function, you will replace a string specified in the first argument with a string specified in the second argument. The third argument is a string or an array in which search and replacement will take place. PHP str_replace
returns a string or an array with the replaced values.
Let's see a simple example:
Correct Syntax
Here we have is a simple scheme for the correct syntax of the PHP string replace function:
str_replace(find, replace, string, count)
In the table below, each parameter of the function is described separately for you to get a better idea:
Parameter | Description |
---|---|
find | Necessary. Defines the value that has to be found. |
replace | Necessary. Defines the replacement value. |
string | Necessary. Specifies a string where the search will take place. |
count | Not necessary. Sets a variable that counts the changes made. |
Code Examples
In the example you can see below, PHP string replace function finds the word cat
in the $arr
array and replaces it with the word lama
. We only have one change done in this case, but the function would successfully replace all the words cat
if the code would consist of more than one.
Variable $i
holds a value of how many replacements did the function do:
<?php
$arr = array("Best", "pet", "is", "cat");
print_r(str_replace("cat", "lama", $arr, $i));
echo "Replace count: $i";
?>
In the example below, PHP str_replace
function replaces two strings in the $arr
array with the letter B. See for yourself:
<?php
$find = array("Hello", "world");
$replace = "B";
$arr = array("Hello", "world", "!");
print_r(str_replace($find, $replace, $arr));
?>