str_ireplace()
The str_ireplace() function in PHP replaces all occurrences of a search string with a replacement string, ignoring case sensitivity. This function is particularly useful when the exact casing of the target text is unknown or varies. In this article, we will discuss the syntax and usage of str_ireplace(), along with practical examples.
The syntax of the str_ireplace() function is as follows:
The PHP syntax of str_ireplace()
mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )The function takes three required parameters: $search, $replace, and $subject. $search specifies the string (or array of strings) to search for, $replace specifies the replacement string (or array of strings), and $subject is the original string. The function also accepts an optional fourth parameter, $count, which is a variable that will be filled with the number of replacements made.
Here is an example of how to use the str_ireplace() function:
Example of PHP str_ireplace()
<?php
$string = "The quick brown fox jumps over the lazy dog";
$new_string = str_ireplace("FOX", "cat", $string);
echo $new_string; // Output: The quick brown cat jumps over the lazy dog
?>In this example, we have a string variable $string that contains the phrase "The quick brown fox jumps over the lazy dog". We use the str_ireplace() function to replace the word "fox" with "cat". Because str_ireplace() is inherently case-insensitive, it will ignore the case of the search string "FOX" and replace it with "cat".
The output of this code will be:
The quick brown cat jumps over the lazy dogAs you can see, the str_ireplace() function has successfully replaced the word "fox" with "cat" in the string, while ignoring the case sensitivity.
The str_ireplace() function is a useful tool for replacing a string in a given string with another string, ignoring case sensitivity. It allows you to easily replace a string in a case-insensitive manner in PHP. By mastering this function, you can become a more proficient PHP developer.
We hope this article has been helpful in understanding the str_ireplace() function in PHP.
Practice
What does the str_ireplace() function in PHP do?