PHP VERSION: 8.2.18

preg_replace_callback_array.php

<?php
// preg_replace_callback_array()
// uses preg_replace_callback_array() to update old version of phpLDAPadmin
// looking for instances of "preg_replace('/xxx/e', yyy, zzz)"

// get name of all files in $lib
$lib __DIR__ '/phpLDAPadmin/lib/';
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($lib),
                                         
RecursiveIteratorIterator::SELF_FIRST);
$count 0;
foreach(
$objects as $name => $fileObj){
    
// his is the filename
    
if ($fileObj->isFile()) {
        
$contents file($name);
        echo 
'Processing: ' $name PHP_EOL;
        
preg_replace_callback_array(
            [
                
// 1   2                 3          4        5
                
"!(.*)(preg_replace)\(\'(.*?\/e)\',(\".*?\")(.*)!" =>
                function (
$match) {
                    echo 
'OLD: ' PHP_EOL trim($match[0]) . PHP_EOL;
                    
$replace $match[1]
                            . 
"preg_replace_callback('"
                            
substr($match[3], 0, -1)
                            . 
"',"
                            
'function ($a) { return "\'" . chr(hexdec($a)) . "\'"; }'
                            
$match[5] . PHP_EOL;
                    echo 
'NEW:' PHP_EOL trim($replace) . PHP_EOL;
                },
                
// additional transformations
                // "/pattern/" => function ($match) { // code; },
            
],
            
$contents
        
);
    }
}



Output


Processing: /homepages/22/d414837955/htdocs/repo/php7_examples/phpLDAPadmin/lib/ds_ldap.php
OLD: 
$a[$key] = preg_replace('/\\\([0-9A-Fa-f]{2})/e',"''.chr(hexdec('\\1')).''",$rdn);
NEW:
$a[$key] = preg_replace_callback('/\\\([0-9A-Fa-f]{2})/',function ($a) { return "'" . chr(hexdec($a)) . "'"; },$rdn);
OLD: 
return preg_replace('/\\\([0-9A-Fa-f]{2})/e',"''.chr(hexdec('\\1')).''",$dn);
NEW:
return preg_replace_callback('/\\\([0-9A-Fa-f]{2})/',function ($a) { return "'" . chr(hexdec($a)) . "'"; },$dn);
Processing: /homepages/22/d414837955/htdocs/repo/php7_examples/phpLDAPadmin/lib/functions.php
OLD: 
$a[$key] = preg_replace('/\\\([0-9A-Fa-f]{2})/e',"''.chr(hexdec('\\1')).''",$rdn);
NEW:
$a[$key] = preg_replace_callback('/\\\([0-9A-Fa-f]{2})/',function ($a) { return "'" . chr(hexdec($a)) . "'"; },$rdn);
OLD: 
return preg_replace('/\\\([0-9A-Fa-f]{2})/e',"''.chr(hexdec('\\1')).''",$dn);
NEW:
return preg_replace_callback('/\\\([0-9A-Fa-f]{2})/',function ($a) { return "'" . chr(hexdec($a)) . "'"; },$dn);
SOURCE CODE