How do I access a variable inside of preg_replace_callback?

瘦欲@ 提交于 2020-01-13 07:50:07

问题


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====

回答1:


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

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

better than polluting the global space



来源:https://stackoverflow.com/questions/16445991/how-do-i-access-a-variable-inside-of-preg-replace-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!