4

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.

Community
  • 1
  • 1
warren
  • 32,620
  • 21
  • 85
  • 124

2 Answers2

6
$content = preg_replace('/{([^{}]*)}/', "<strong>$1</strong>", $content);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
  • 1
    you need to change `{something}` , so you put the `{` and `}` , now you need to get whats inside of them with `(.*)` , but you don't need whats inside to be { or } , so you just say (anything except { or }) .. like not [ { or } ] = ^[{|}] . i suck in explaining thing , my boss does not care as long as i get the job done ... – Rami Dabain Feb 01 '11 at 15:59
  • 3
    That `[^{|}]` should be just `[^{}]`. There's no need for an "or" operator in a character class, so `|` loses its special meaning and just matches `|`. – Alan Moore Feb 01 '11 at 20:13
4

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • 2
    I've never heard of parentheses referred to as "round braces." but otherwise, +1 – Stephen Feb 01 '11 at 15:31
  • 4
    @warren: Ronans match pattern is more resilient against erroneously mixed braces. While `.+?` is often sufficient to match the shortest possible string, the `[^}]+` negative character class is a more professional idiom. In your case I would consider it interchangable however. – mario Feb 01 '11 at 15:43