Skip to content

Instantly share code, notes, and snippets.

@tournasdim
Created July 13, 2014 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tournasdim/0e62b8464ec85521c0da to your computer and use it in GitHub Desktop.
Save tournasdim/0e62b8464ec85521c0da to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment