Created
July 13, 2014 10:30
-
-
Save tournasdim/0e62b8464ec85521c0da to your computer and use it in GitHub Desktop.
An example of PHP's preg_replace_callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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