Replacing Patterns in a String
Problem
You want to replace all/some occurrences of a pattern or substring within a string
with something else.
Solution
Use a regular expression in combination with PHP’s str_replace() function (for
simple patters):
<?php
// define string
$str = “Michael says hello to Frank”;
// replace all instances of “Frank” with “Crazy Dan”
// result: “Michael says hello to Crazy Dan”
$newStr = str_replace(“Frank”, “Crazy Dan”, $str);
echo $newStr;
?>
For more complex patters, use a regular expression in combination with PHP’s
preg_replace() function:
<?php
// define string
$html = “I’m <b>tired</b> and so I <b>must</b> go ↵
<a href=’http://domain’>home</a> now”;
// replace all bold text with italics
// result: “I’m <i>tired</i> and so I <i>must</i> go
<a href=’http://domain’>home</a> now”
$newStr = preg_replace(“/<b>(.*?)<\/b>/i”, “<i>\\1</i>”, $html);
echo $newStr;
?>