PHP preg_replace_callback

The preg_replace_callback() function is an under-utilized and little documented PHP function that you will find useful and powerful in many situations, especially if you have been actively using preg_match() and preg_replace().

<?php
echo $t1 = 'Lorem ipsum <insert>130</insert> dolor sit amet, adipiscing <insert>150</insert> elit.';

function fReplace($matches) { echo '<pre>'; print_r($matches); echo '</pre>'; return $matches[0] = '<b>INSERT TEXT</b>'; } echo preg_replace_callback('/<insert>.*?</insert>/siu','fReplace',$t1); ?>

IN => Lorem ipsum <insert>130</insert> dolor sit amet, adipiscing <insert>180</insert> elit.

OUT => Lorem ipsum INSERT TEXT dolor sit amet, adipiscing INSERT TEXT elit.

Related Posts

Replace Link Value PHP, PHP remove white space from the beginning and end of a string