PHP Tutorial - PHP str_replace() Function






Definition

PHP str_replace() Function replace all occurrences of the search string with the replacement string.

Syntax

PHP str_replace() Function has the following syntax.

mixed str_replace ( mixed needle, mixed replace, mixed haystack [, int &count] )

Parameter

The str_replace() function replaces a string with new strings. str_replace() function takes a minimum of three parameters:

  • what to look for,
  • what to replace it with, and
  • the string to work with.

count If passed, this will be set to the number of replacements performed.





Return

This function returns a string or an array with the replaced values.

Example

str_replace() is case sensitive. case-insensitive version of str_replace() is str_ireplace().

<?PHP
$string = "aaa"; 
$newstring = str_ireplace("A", "b", $string); 
print $newstring; 
?>

When used, the fourth parameter is passed by reference, and PHP will set it to be the number of times your string was found and replaced:

<?PHP
$string = "java php from j a v a 2 s . c o m."; 
$newstring = str_replace("java", "php", $string, $count); 
print "$count changes were made.\n"; 
print $newstring;
?>