Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a variable inside of preg_replace_callback?

I'm trying to replace {{key}} items in my $text with values from a passed array. but when I tried adding the print_r to see what was going on I got a Undefined variable: kvPairs error. How can I access my variable form within the preg_replace_callback?

public function replaceValues($kvPairs, $text) {
    $text = preg_replace_callback(
        '/(\{{)(.*?)(\}})/',
        function ($match) {
            $attr = trim($match[2]);
            print_r($kvPairs[strtolower($attr)]);
            if (isset($kvPairs[strtolower($attr)])) {
                return "<span class='attr'>" . $kvPairs[strtolower($attr)] . "</span>";
            } else {
                return "<span class='attrUnknown'>" . $attr . "</span>";
            }
        },
        $text
    );
    return $text;
}

Update:

I've tried the global scope thing, but it doesn't work either. I've added 2 print statements to see whats doing on, one inside and one outside the preg_replace_callback.

public function replaceValues($kvPairs, $text) {
    $attrTest = 'date';
    print_r("--" . strtolower($attrTest) . "--" . $kvPairs[strtolower($attrTest)] . "--\n");
    $text = preg_replace_callback(
        '/(\{{)(.*?)(\}})/',
        function ($match) {
            global $kvPairs;
            $attr = trim($match[2]);
            print_r("==" . strtolower($attr) . "==" . $kvPairs[strtolower($attr)] . "==\n");
            if (isset($kvPairs[strtolower($attr)])) {
                return "<span class='attr'>" . $kvPairs[strtolower($attr)] . "</span>";
            } else {
                return "<span class='attrUnknown'>" . $attr . "</span>";
            }
        },
        $text
    );
    return $text;
}

The output I get is:

--date--1977-05-20--
==date====
like image 478
Justin808 Avatar asked May 08 '13 16:05

Justin808


1 Answers

As your callback function is a closure, you can pass extra arguments via use

function ($match) use ($kvPairs) {
    ...
}

better than polluting the global space

like image 108
Mark Baker Avatar answered Oct 20 '22 03:10

Mark Baker