Because PHP is a single threaded procedural scripting language1, it doesn't work in the way you want it to.
It is not possible to trigger the function to run only when you call echo
2, what you need instead is an extra variable.
$newVariable = preg_replace_callback("#\[%(.{1,20})%\]#", function($matches) {
// Do your thang here
}, $maintext);
// $maintext remains the same as it was when you started, do stuff with it here
// When you come to output the data, do...
echo $newVariable;
There are other approaches to this problem, like wrapping the above code in a function that can be called on demand and using the output buffering callback (see footnote #2), but reading between the lines I think all of this would be overkill for what is a relatively simple problem.
For the record, I think your regex would be better if you narrow the allowed content down a it, it will potentially match characters you don't want it to. I suspect that this would be better:
#\[%(\w{1,20})%\]#
This will allow only the characters a-zA-Z0-9_
in the placeholder.
1 Others may tell you PHP is now an object oriented language, but they are wrong. It still fundamentally works the same underneath and its still a scripting language, but now provides many OO-features.
2 It is possible to do something very close to this, but it is very rarely ever a good idea and is far too advanced for dealing with this problem.
EDIT
It is important to note that when using either method to pass replacements through a callback (e
modifier or preg_replace_callback()
) the callback function should return the new string, rather than outputting it directly.
This is because the code in any statement is executed from the inside out, and the "inner" echo
statement (in the callback function) will be executed before the "outer" echo
statement (on the line where preg_replace()
is called, so the order in which things are output will be incorrect.
For example:
$str = "This is my string which contains a %placeholder%";
echo preg_replace_callback('/%(\w+)%/', function($matches) {
echo "replacement string";
}, $str);
// Wrong - outputs "replacement stringThis is my string which contains a "
echo preg_replace_callback('/%(\w+)%/', function($matches) {
return "replacement string";
}, $str);
// Right - outputs "This is my string which contains a replacement string"