Introduction
In this article I will explain pattern replacement in a string using PHP. I am using the simple functions "str_replace()" and "preg_replace()". Assume you want to replace the occurrence of a pattern or substring within a string. That requires use of a function to replace the patterns. You can use str_replace() for a simple pattern and for more complex patterns use the preg_replace() function in PHP.
For simple applications that you do not need more complex pattern or regular expressions, consider the str_replace() function instead of a regular expression with this function. The str_replace function is faster than the preg_replace function. In str_replace, you can replace the one substring or one replacement string but the preg_replace function takes a preg_match function to step forward and search for a regular expression matching in a string target.
Example
<?php
// define string
$str = "Hii.. My name is vinod";
$SStr = str_replace("vinod", "Sharad", $str);
echo $SStr."<br>";
?>
Output
Potential str_replace() gotcha
<?php
$str = "Line 1."<br>".Line 2."<br>".Line 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $str);
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace,$subject);
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Output
The preg_replace() function performs a regular expression search and replace and preg_replace() function uses a Perl compliant regular expression and it returns the original value of the string. If the preg_replace function cannot find a match then it returns the original string.
Example
Using back references followed by numeric literals
<?php
$str = 'April 15, 2003';
$ptr = '/(\w+) (\d+), (\d+)/i';
$rplc = '${1},$3';
echo preg_replace($ptr, $rplc, $str);
?>
Output
Using Index Array
<?php
$str = 'The quick brown fox jumped over the lazy dog.';
$ptr = array();
$ptr[0] = '/quick/';
$ptr[1] = '/brown/';
$ptr[2] = '/fox/';
$rplc = array();
$rplcs[2] = 'bear';
$rplc[1] = 'black';
$rplc[0] = 'slow';
echo preg_replace($ptr, $rplc, $str);
?>
Output
By default both functions replace all occurrences of the search strings with the replacement string. You can pass the fourth parameter for counting the replacement string. The fourth parameter is optional. Such as:
Example
<?php
$string = "Michael says hello to Frank. Frank growls at Michael. Michael
feeds Frank a bone.";
$SStr = str_replace("Frank", "Crazy Dan", $string, $counter);
echo "$counter replacement(s)";
?>
Output