PHP String Replace

String replace functions are most important and frequently used in php for string manipulaion. You can replace all sub-strings in a string or only some of them. You can replace word or character from main string.

PHP has the following built in string manipulation function to replace strings:

  • str_replace
  • str_ireplace
  • preg_replace

str_replace  

str_replace function replaces all occurrences of the search string with the replacement string.  The syntax of str_replace is as follows:

mixed str_replace ( $search, $replace, $subject )

$search: the word you are searching
$replace: the word which you want to replace with $search
$subject: the word/line that you are defiend where you are search word using $search varialble.

Example:
<?php
$originalString = "I like New York because it is my city.";
$newString = str_replace("New York ","London",$originalString);
echo $originalString."<br/>";
echo $newString."<br/>";
?>

str_ireplace
This function is very similar to str_replace but it is case-insensitive.

preg_replace
This function performs a regular expression search and replace. The syntax is the following:
mixed preg_replace ( mixed $pattern, mixed $replacement, mixed $subject [, int $limit [, int &$count]] )
An example code:

<?php
$originalString = August 03, 2007';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1} 01,$3';
echo preg_replace($pattern, $replacement, $originalString);
?>

Bookmark This Page

Link Partners