PHP str_ireplace()Function
Examples
Replace the characters "WORLD" (case-insensitive) in the string "Hello world!" with "Peter":
<?php
echo str_ireplace("WORLD","Peter","Hello world!");
?>
echo str_ireplace("WORLD","Peter","Hello world!");
?>
Run example »
Definition and Usage
The str_ireplace() function replaces some characters in a string (case-insensitive).
This function must follow the following rules:
- If the string being searched is an array, it returns an array.
- If the string being searched is an array, it will search and replace each element in the array.
- If you need to search and replace in an array, and the elements to be replaced are fewer than the elements found, then the remaining elements will be replaced with an empty string.
- If you are searching an array but replacing with only one string, then the replacement string will apply to all found values.
Note:This function is case-insensitive. Use thestr_replace()function to perform a case-sensitive search.
Note:This function is binary-safe.
Syntax
str_ireplace(find,replace,string,count)
| Parameter | Description |
|---|---|
| find | Required. Specifies the value to find. |
| replace | Required. Specifies the value to replacefindthe value in find. |
| string | Required. Specifies the string to be searched. |
| count | Optional. A variable that counts the number of replacements. |
Technical Details
| Return value: | Returns a string or an array with the replaced values. |
|---|---|
| PHP Version: | 5+ |
| Changelog: | In PHP 5.0, thecountparameter was added. |
More Examples
Example 1
Use the str_ireplace() function with an array and a count variable:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i)); // This function is case-insensitive
echo "Replacements: $i";
?>
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i)); // This function is case-insensitive
echo "Replacements: $i";
?>
Run example »
Example 2
Use the str_ireplace() function with fewer elements to replace than elements found:
<?php
$find = array("HELLO","WORLD"); // This function is case-insensitive
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_ireplace($find,$replace,$arr));
?>
$find = array("HELLO","WORLD"); // This function is case-insensitive
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_ireplace($find,$replace,$arr));
?>
Run example »
PHP String Reference Manual Other Extensions