Jump to content

preg_match_all for string between {} or "braces"


bluebyyou

Recommended Posts

<?php

$str = "Some {sample|example|variable} text. More {text|things|stuff} text.";

$pattern ="/\{.*\}/is";

preg_match_all($pattern, $str, $matches);

foreach ($matches as $val)
{
print_r($val);
}

?>

 

It outputs:

 

Array ( [0] => {sample|example|variable} text. More {text|things|stuff} )

 

-------------

 

What I want the output to be is each string between the {}'s to be parsed out individually, I just am having a hell of a time writing the proper regular expression. Can someone point me in the right direction?

 

 

Link to comment
Share on other sites

It's because by default .* is a greedy search, meaning it will keep matching whilst it can. You could make the search lazy by adding a question mark after the .* match. Personally thought I'd opt to use [^}]* as your match instead.

 

'#\{[^}]*\}#s'

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.