PHP replace everything between curly brackets?

2019-07-03 12:15发布

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?

2条回答
Juvenile、少年°
2楼-- · 2019-07-03 12:48

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.

查看更多
ら.Afraid
3楼-- · 2019-07-03 12:50

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.
查看更多
登录 后发表回答