php - How do I access a variable inside of preg_replace_callback? -
i'm trying replace {{key}}
items in $text
values passed array. when tried adding print_r
see going on got undefined variable: kvpairs
error. how can access variable form within 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 global
scope thing, doesn't work either. i've added 2 print statements see whats doing on, 1 inside , 1 outside 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 is:
--date--1977-05-20-- ==date====
as callback function closure, can pass arguments via use
function ($match) use ($kvpairs) { ... }
better polluting global space
Comments
Post a Comment