Matching text between braces in PHP

只愿长相守 提交于 2019-12-05 01:03:16

问题


In direct follow-up to this previous question, how can I pull the text (and the braces if possible) out as a match using PHP?

Specifically, I am writing a Wordpress plugin and am looking to reformat all text between two curly braces (a quasi wiki-marking).

I've followed the steps outlined in another previous question I asked, and have the matching part working - it's the match I need help with.

Example:

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

Desired output:

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

What I have (that is not working):

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

If matching including the braces is too difficult, I can match using the braces as offsets, and then remove the 'offending' braces afterwards, too, using a more simple text-match function.


回答1:


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



回答2:


You need to form a match group using ( round braces ).

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

Whatever (.+?) matches then can be used as $1 in the replacement string. This way you have the enclosing {{ and }} already out of the way. Also \b was redundant.



来源:https://stackoverflow.com/questions/4864328/matching-text-between-braces-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!