How to use preg_replace in php to replace text with function result?
I have a complicated problem: I have a very long text and I need to call some php f开发者_运维知识库unctions inside my text. The function name is myfunction(); I`we included in my text the function in the following way: " text text text myfunction[1,2,3,4,5]; more text text ... "
And I want to replace each myfunction[...] with the result of the function myfunction with the variables from the [] brackets.
my code is:
<?php echo preg_replace('/myfunction[[0-9,]+]/i',myfunction($1),$post['content']); ?>
,but it`s not working.
The parameter should be an array, because it can contain any number of values.
If I were you, I would avoid using the e
modifier to preg_replace
because it can lead you open to execution of arbitrary code. Use preg_replace_callback
instead. It's slightly more verbose, but much more effective:
echo preg_replace_callback('/myfunction\[([0-9,]+)\]/i', function($matches) {
$args = explode(',', $matches[1]); // separate the arguments
return call_user_func_array('myfunction', $args); // pass the arguments to myfunction
}, $post['content']);
This uses an anonymous function. This functionality won't be available to you if you use a version of PHP before 5.3. You'll have to create a named function and use that instead, as per the instructions on the manual page.
You can use preg_replace()
's "e" modifier (for EVAL) used like this :
$text = preg_replace('/myfunction\[(.*?)\]/e', 'myfunction("$1")', $text);
I didn't really get how your data is structured so it's all I can do to help you at the moment. You can explore that solution.
From the PHP Manual :
e (PREG_REPLACE_EVAL) If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes () and NULL chars will be escaped by backslashes in substituted backreferences.
You need to add the "e" modifier, escape [
and ]
in the regex expression and stringify the second argument.
preg_replace('/myfunction\[[0-9,]+\]/ei','myfunction("$1")',$post['content']);
精彩评论