Search code examples
phppreg-replace-callback

preg_replace_callback with PHP 5.2.17


I have this code and its working fine with PHP 5.3 onwards but i need to run it from 5.2.17 onwards please anybody help me with this.

$data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');

$template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#"; 

$result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', function ($match) use($data) {
$value = "";
$dataMatch = $data[$match[1]];
if (!isset($dataMatch)) {
    // undefined variable in template throw exception or something ...
} else {
    $value = $dataMatch;
}

if (! empty($match[2]) && $match[1] == "date") {
    $value = date($match[2], $value);
}

return $value;
}, $template);

echo $result;

Solution

  • First name your replacing function and define it before callback, remember to take care of $data as global, since it wouldn't be passed by preg_replace

    function my_replace_function($match){
        global $data;
        $value = "";
        $dataMatch = $data[$match[1]];
        if (!isset($dataMatch)) {
            // undefined variable in template throw exception or something ...
        } else {
            $value = $dataMatch;
        }
    
        if (! empty($match[2]) && $match[1] == "date") {
            $value = date($match[2], $value);
        }
    
        return $value;
    }
    

    now simply use it's name in string form:

    $result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/','my_replace_function', $template);