PHP str_replace: Main Tips
- By using this function, you can replace characters in a text string.
str_replaceis case-sensitive. If you need to perform a case-insensitive search, try
- 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.
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:
echo str_replace("world","Peter","Hello world!");
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:
|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.|
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.
$i holds a value of how many replacements did the function do:
array("Best", "pet", "is", "cat"); print_r(str_replace("cat", "lama", $arr, $i)); echo "Replace count: $i";$arr =
In the example below, PHP
str_replace function replaces two strings in the
$arr array with the letter B. See for yourself:
array("Hello", "world"); $replace = "B"; $arr = array("Hello", "world", "!"); print_r(str_replace($find, $replace, $arr));$find =
Latest Coupon Found:
TOP-RATED CODING COURSES
Learn the skills of tomorrow
The best time to learn programming is now - follow this link to access 100+ coding courses and enjoy learning at a very low cost!