Monday, 29 September 2014

str_ireplace in PHP

PHP str_ireplace() function is utilized to replace target substrings with another string.
Returns a copy of the containing string with all instances of the first argument replaced by the second argument.

The rules followed by function :

If the string to be searched is an array, it returns an array
If the string to be searched is an array, find and replace is performed with every array element
If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
If find is an array and replace is a string, the replace string will be used for every find value
Syntax:

str_ireplace(find,replace,string,count)
find : Required.Specifies the substring to search for.

replace : Required. Specifies the string to replace it with

string : Required. Specifies the containing string.

count : Optional. counts the number of replacements of a variable.

Note: This function is binary-safe and case-insensitive. For case-sensitive use str_replace() function.

Example:

<?php
echo str_ireplace("MORNING", "Night", "Good Morning");
echo "<br /> Example with an array and count variable <br />";
$arr_name = array("cricket","football","basketball");
print_r(str_ireplace("basketball","handball",$arr_name,$i));
echo "<br /> Repalcement counts : $i <br />";
echo "Example with less elements in replace than find : <br />";
$arr_find = array("basketball","cricket");
$arr_replace = array("handball");
$arr_name = array("basketball","cricket","football");
print_r(str_ireplace($arr_find,$arr_replace,$arr_name));
?>
Output will be:
Good Night
Example with an array and count variable
Array (
         [0] => cricket
         [1] => football
         [2] => handball
       )
Repalcement counts : 1
Example with less elements in replace than find :
 Array (
          [0] => handball
          [1] =>
          [2] => football
          )

0 comments:

Post a Comment