How to replace string using PHP

Last updated on February 11th, 2022 at 07:21 am

Click to rate this tutorial!
[Total: 1 Average: 1]

Replace string using PHP with demo

Simple code to replace a string using and limit occurrence.

Using preg_replace we can provide the limit of replacement. There are 2 output in the script, one is with count 1 which means it will only replace the first occurrence of abc and ignores the rest and the other is without any count. Since there is no count in the second output it will replace the entire string where the match abc is found with 123

ereg_replace has been DEPRECATED as of PHP 5.3.0 and we are not using that in our examples any more.

$var='abcdef abcdef abcdef';
//pattern, replacement,string
echo "<h2>Using preg_replace</h2>";
echo "<b>With 1 :</b>".preg_replace('/abc/','123',$var,1);
echo "<hr>";
echo "<b>With nothing, no count given :</b>".preg_replace('/abc/','123',$var)


Click to rate this tutorial!
[Total: 1 Average: 1]

Leave a Reply

Your email address will not be published.