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

war*_*ren 4 php regex wordpress plugins wordpress-plugin

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

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

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

例:

This is some {{text}} and I want to reformat the items inside the curly braces
Run Code Online (Sandbox Code Playgroud)

期望的输出:

This is some *Text fancified* and I want to reformat the items inside the curly braces
Run Code Online (Sandbox Code Playgroud)

我有什么(即工作):

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

如果包括大括号的匹配太难,我可以使用大括号作为偏移进行匹配,然后使用更简单的文本匹配功能删除'违规'大括号.

Ron*_*ero 6

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

  • 那个`[^ {|}]`应该只是`[^ {}]`.字符类中不需要"或"运算符,因此`|`失去了它的特殊含义,只匹配`|`. (3认同)