在PHP中使用大括号匹配文本

时间:2011-02-01 15:19:23

标签: php regex wordpress plugins wordpress-plugin

在前一个question的直接跟进中,如何使用PHP将文本(以及可能的大括号)拉出来作为匹配?

具体来说,我正在编写一个Wordpress插件,我希望重新格式化两个花括号之间的所有文本(准wiki标记)。

我已按照我之前提到的另一个question中列出的步骤进行操作,并让匹配部分正常工作 - 这是我需要帮助的匹配

示例:

This is some {{text}} and I want to reformat the items inside the curly braces

期望的输出:

This is some *Text fancified* and I want to reformat the items inside the curly braces

我拥有的(正在工作):

$content = preg_replace('#\b\{\{`.+`\}\}\b#', "<strong>$0</strong>", $content);

如果匹配包括大括号太难了,我可以使用大括号作为偏移匹配,然后使用更简单的文本匹配功能删除'违规'大括号。< / p>

2 个答案:

答案 0 :(得分:6)

$content = preg_replace('/{([^{}]*)}/', "<strong>$1</strong>", $content);

答案 1 :(得分:4)

您需要使用(圆括号)形成匹配组。

preg_replace('#\{\{(.+?)\}\}#', "<strong>$1</strong>",

无论(.+?)匹配什么,都可以在替换字符串中用作$1。通过这种方式,您可以将封闭的{{和}}放在一边。 \b也是多余的。