PHP of course performs variable replacement on double quoted strings:
$test = 'something';
echo "This is a $test";
//Output: This is a something
What I'm looking for is PHP's variable replacement but with callback:
function callback($key, &$value) {
$value=strtoupper($value);
}
$test = 'something';
echo some_cool_function('This is a $test', callback);
//Output: This is a SOMETHING
(Of course that was a totally arbitrary example - I am not looking to do something as simple as converting values to uppercase.)
Thus callback
would then be called for each variable (or perhaps with an array of all variables like '$test' => 'something'
). That way I can directly manipulate and otherwise work with the variables and replacement values PHP performs.
I know something similar can be done with regular expressions with callback and the like. However, there is extra complexity in how PHP handles variables like $test[0]
, complex syntax ({ }
), etc that may be convoluted to work with.
Does PHP expose its internal string parser used for double quoted strings in some way?
If I understand correctly, you intending that some_cool_function
would apply the function callback
to the string 'This is a $test'
.
Referencing the callback function by using a variable will do the trick:
$cb = callback;
$test = 'something';
echo "This is a {$cb($test)}";