PHP str_ireplace() Function
Topic: PHP String ReferencePrev|Next
Description
The str_ireplace()
function replaces all occurrences of a string with another string.
This function is a case-insensitive version of the str_replace()
function.
The following table summarizes the technical details of this function.
Return Value: | Returns a string or an array with the replaced values. |
---|---|
Version: | PHP 5+ |
Syntax
The basic syntax of the str_ireplace()
function is given with:
The following example shows the str_ireplace()
function in action.
Example
Run this code »<?php
// Sample string
$str = "Twinkle twinkle little star";
// Performing replacement
echo str_ireplace("Twinkle", "Shiny", $str);
?>
If find and replace are arrays, then str_ireplace()
takes a value from each array and uses them to find and replace on string, as you can see in the following example:
Example
Run this code »<?php
// Sample string
$str = "My favorite colors are: red, green, and blue.";
// Defining find and replace arrays
$find = array("RED", "Green", "blue");
$replace = array("black", "yellow", "purple");
// Performing replacement
echo str_ireplace($find, $replace, $str);
?>
If replace array has fewer values than the find array, then an empty string will be used for the rest of replacement values. Let's check out an example to understand how it works.
Example
Run this code »<?php
// Sample string
$str = "Cheetah and the lion run very fast.";
// Defining find and replace arrays
$find = array("cheetah", "lion", "very");
$replace = array("dog", "bull");
// Performing replacement
echo str_ireplace($find, $replace, $str);
?>
If find is an array and replace is a string, then the replace string will be used for every find value.
Example
Run this code »<?php
// Sample string
$str = "They sang and danced till night.";
// Defining find array and replace string
$find = array("sang", "danced");
$replace = "talked";
// Performing replacement
echo str_ireplace($find, $replace, $str);
?>
Parameters
The str_ireplace()
function accepts the following parameters.
Parameter | Description |
---|---|
find | Required. Specifies the value to find or search. |
replace | Required. Specifies the replacement value that replaces found values. |
string | Required. Specifies the string to be searched. |
count | Optional. Specifies a variable that will be set to the number of replacements performed. |
More Examples
Here're some more examples showing how str_ireplace()
function actually works:
The following example demonstrates how to find the number of replacements performed:
Example
Run this code »<?php
// Sample string
$str = "Rain rain go away";
// Performing replacement
str_ireplace("Rain", "Sun", $str, $count);
echo "Number of replacements performed: $count";
?>