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====
As your callback function is a closure, you can pass extra arguments via use
function ($match) use ($kvPairs) {
...
}
better than polluting the global space
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With