Monday, 29 September 2014

str_replace in PHP

PHP str_replace() 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.

Syntax:

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

replace : Required. Specifies the string to replace it

string : Required. Specifies the containing string.

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

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

Example:

<?php
echo str_replace("Morning", "Night", "Good Morning");
echo "<br /> Example with an array and count variable <br />";
$arr_name = array("cricket","football","basketball");
print_r(str_replace("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_replace($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