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?

 

 

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'

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.