0

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;
alladeen
  • 13
  • 5
  • Stackoverflow is not a free code translation service. If you're too lazy to even read documentation - please hire someone to do that for you. – zerkms Nov 02 '12 at 08:25
  • `preg_replace_callback()` is available since PHP/4.0.5 – Álvaro González Nov 02 '12 at 08:26
  • 1
    @Álvaro G. Vicario: I'm sure he's experiencing issues because of anonymous function. – zerkms Nov 02 '12 at 08:26
  • @ÁlvaroG.Vicario: Sure, the function isn't new, but lambda-style anon. functions weren't around back then. [There are examples in the man pages](http://php.net/manual/en/function.preg-replace-callback.php) that pre-date anon. function support, so the OP should RTFM – Elias Van Ootegem Nov 02 '12 at 08:29
  • @zerkms you got it right 'anonymous function' is my problem and i am trying to understand how i could use those. And i am not lazy for anything i am learning and if you cant help please don't make those remarks. – alladeen Nov 02 '12 at 08:31
  • @alladeen: create regular named function and pass its name as a string. – zerkms Nov 02 '12 at 08:31
  • 1
    You're all right. I admit I don't really dig into code that's dumped at Stack Overflow without further information. If the OP doesn't care about his question, neither do I :) – Álvaro González Nov 02 '12 at 08:40

1 Answers1

2

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);
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85