Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace everything between curly brackets?

I suck with preg I will never learn it :( This shouldn't be hard can I please have a code example to replace everything between curly brackets, including spaces, everything? Like:

$string = preg_replace('{.*?}#si', '', $string); 

or something?

like image 520
John Jenkins Avatar asked Oct 03 '11 21:10

John Jenkins


2 Answers

You were missing the initial # delimiter:

'#\{.*?\}#s'

See it working online: ideone

A couple of other minor points:

  • The i modifier is unnecessary here since you don't have any letters in the pattern.
  • It's a good idea to escape { and } in regular expressions to avoid confusion with their use as quantifiers, though it's not strictly necessary in this case.
like image 109
Mark Byers Avatar answered Oct 07 '22 20:10

Mark Byers


After reading your other questions, it seems that you want to use this for beautifying your code. While many editors have this functionality built into them for a single file, I imagine you want to apply this to a bunch of files. If this is the case, see https://github.com/clbustos/PHP_Beautifier.

Edit due to comments: Then you won't want to use regex, honestly. Use the php tokenizer.

like image 31
Levi Morrison Avatar answered Oct 07 '22 20:10

Levi Morrison