我知道不推荐使用eval(),我也很清楚,我不需要知道这不是一种安全的方法:)
我只需要一个解决方案。
我想评估来自mySQL DB的字符串的代码,但我想应用一个过滤器。
我的意思是,只有在括号内为{$code}时,eval()才会对代码求值。
我如何才能做到这一点?
谢谢
发布于 2012-01-31 06:27:43
$resultFromDb ='"blah blah blah {echo "Hello world";} blah blah blah';
preg_match('#\{(.*)\}#', $resultFromDb, $matches); // do your own error-checking here
$codeToEval = $matches[1];
eval($codeToEval);发布于 2012-01-31 06:30:34
你也许可以使用preg_replace_callback (如果你不需要前面函数的上下文)。示例:
function runCode( $matches){
eval( $matches[1]);
}
preg_replace_callback( '~\\{(.*?)\\}~', 'runCode', $text);如果您需要以前的上下文,最好的方法是从$text创建临时文件,并用<?php .... ?>替换{...} ...
发布于 2012-01-31 06:30:35
preg_replace_eval的用法可以是带有修饰语e的option(preg_replace )
示例:
$v='variable';
$i=123;
$s='this is a string';
$string = 'some {$v} and a instruction {++$i;} and a function-call: {strtoupper($s)} ';
echo preg_replace('@\{([^\{\}]+)\}@e',
"$1",
$string);返回:
some variable and a instruction 124 and a function-call: THIS IS A STRING https://stackoverflow.com/questions/9071728
复制相似问题