tournasdim
7/13/2014 - 10:30 AM

An example of PHP's preg_replace_callback

An example of PHP's preg_replace_callback

// This function is part of Laravel's ./Illuminate/Support/helpers.php:663:	
function preg_replace_sub($pattern, &$replacements, $subject)
{
    return preg_replace_callback($pattern, function($match) use (&$replacements)
    {
        return array_shift($replacements);

    }, $subject);
}

$pattern = '/(xyz|klm|xop)/';
$replacements = array('---', '****', 'xxxx');
$subject = 'This is a sample text with random characters xyz, xyz , klm , xop , klm and more'; 
var_dump(preg_replace_sub($pattern , $replacements, $subject));

// using preg_replace_callback standalone
$pattern = '/(xyz|klm|xop)/';
$replacements = array('---', '****', 'xxxx');
$subject = 'This is a sample text with random characters xyz, xyz , klm , xop , klm ,klm , klm, bbb and more'; 
var_dump(preg_replace_callback($pattern, function($match) use (&$replacements)
    {
        return array_shift($replacements);

    }, $subject, -1 , $count));
var_dump($count); // 7