$features = preg_replace_callback('!s:(\d+):"(.*?)";!s', function($c) {
return serialize($c[2]);
}, $features);
When-/Where-ever the pattern matches in the source ($features in the example) the callback is invoked and all captures are passed as an array ($c in the example).
$c[0] is the complete match, $c[1] the first sub-capture (the string that maches \d+
), $c[2] the seconds sub-capture (the string that matches .*?
).
The complete match is replaced by whatever the callback returns.
Take a look at this example:
<?php
echo "
-------- example #1 --------
";
$src = '1a2b3c';
$result = preg_replace_callback('!\d!', function($c) {
cprint($c);
$retval = $c[0]+22;
echo ' cb returns: ', $retval, "
";
return $retval;
}, $src);
echo 'result: ', $result, "
";
echo "
-------- example #2 --------
";
$src = '1a2b3c4a5b6';
$result = preg_replace_callback('!(\d)a(\d)!', function($c) {
cprint($c);
$retval = sprintf('%dA%d', $c[1]+22, $c[2]+33);
echo ' cb returns: ', $retval, "
";
return $retval;
}, $src);
echo 'result: ', $result, "
";
function cprint(array $c) {
echo 'callback invoked
$c=', preg_replace('!\s+!', ' ', var_export($c, true)), "
";
}
prints
-------- example #1 --------
callback invoked
$c=array ( 0 => '1', )
cb returns: 23
callback invoked
$c=array ( 0 => '2', )
cb returns: 24
callback invoked
$c=array ( 0 => '3', )
cb returns: 25
result: 23a24b25c
-------- example #2 --------
callback invoked
$c=array ( 0 => '1a2', 1 => '1', 2 => '2', )
cb returns: 23A35
callback invoked
$c=array ( 0 => '4a5', 1 => '4', 2 => '5', )
cb returns: 26A38
result: 23A35b3c26A38b6