所以在我的 PHP 代码中我有一个像这样的字符串;
The quick brown {{fox($a);}} jumped over the lazy {{dog($b);}}.
现在听起来可能很奇怪,但我想遍历字符串,并收集所有 BBCode 样式标签。
然后我想eval()
{{}}
内的所有函数。所以我会评估 fox($a);
和 dog($b);
。
这两个函数都返回一个字符串。我想用相应的结果替换相应的标签。因此,假设 fox()
返回“vulpes vulpes”并且 dog()
返回“canis lupus”,我的原始字符串将如下所示;
The quick brown vulpes vulpes jumped over the lazy canis lupus.
但是,我对正则表达式的使用是出了名的糟糕,而且我不知道如何解决这个问题。
欢迎任何建议!
(是的,我知道随遇而安 eval()
ing 的危险。但是,这些字符串严格来自开发人员,没有用户能够评估任何内容.)
最佳答案
如果您想使用正则表达式来执行此操作,这里有一个似乎对我有用的解决方案:
function fox( $a) { return $a . 'fox!'; }
function dog( $b) { return $b . 'dog!'; }
$a = 'A'; $b = 'B';
$string = 'The quick brown {{fox($a);}} jumped over the lazy {{dog($b);}}.';
$regex = '/{{([^}]+)+}}/e';
$result = preg_replace( $regex, '$1', $string);
正则表达式非常简单:
{{ // Match the opening two curly braces
([^}]+)+ // Match any character that is not a closing brace more than one time in a capturing group
}} // Match the closing two curly braces
当然,/e
修饰符会导致替换被eval
'd,从而产生以下结果:
输出:
var_dump( $result);
// string(49) "The quick brown Afox! jumped over the lazy Bdog!."
关于php - 匹配、评估和替换 BBCode 样式标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391454/