匹配,评估和替换BBCode样式标签


Match, eval and replace BBCode style tags

所以在我的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()的危险。但是,这些字符串严格来自开发人员,任何用户都无法评估任何内容。

如果您想使用正则表达式执行此操作,这里有一个似乎对我有用的解决方案:

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,产生这个:

输出:

var_dump( $result);
// string(49) "The quick brown Afox! jumped over the lazy Bdog!."

如果你只在这些标签中插入有效的php,你可以做一个

$string = '.....';
$string = '?>' . $string;
$string = str_replace('{{', '<?php echo ', $string);
$string = str_replace('}}', '?>', $string);
ob_start();
eval($string);
$string = ob_get_clean();