Jump to content

get strings within {} - simple regex


joshis

Recommended Posts

I would like to get strings within the '{}' symbols. My expression is like this.

$string = 'The quick brown {fox} jumped {over} the lazy dog.';

$patterns[0] = '/({)+(.)*(})+/';

 

preg_match_all($patterns[0],$string,$matches);

 

foreach($matches[0] as $match)

{

echo( $match).'<br />';

}

 

but it gives result as

{fox} jumped {over}

 

but I need

 

fox

over

 

Can anyone help me?

Link to comment
Share on other sites

Will there be any nested values. What I mean by this is will the source ever take the form of...

 

This is an example {of what {I mean} will it ever be like this? }

 

I don't quite understand the layout of your pattern, for the job described I'd probably opt for something along the lines of...

 

#{\K[^}]*#

Link to comment
Share on other sites

Pending the answer to cags' post, it might also be fine to use something like /{(.+?)}/ (you'd then need to loop over $matches[1]). There are a tonne of varieties of regular expression which might be useful, better, faster, easier, etc. and as usual there's no "one right answer".  If you do need to cater for nested values, then both of our replies will need some rethinking.

Link to comment
Share on other sites

In the event of nested braces, one possible solution could be:

 

Example:

function stripBraces($arr){
   foreach($arr as &$val){
      $val = trim($val, '{}');
   }
    return $arr;
}

$str = 'Some text {of what {I mean} will it ever be like this?} Some more {text}!';
preg_match_all('#{[^{}]*(??R)|.*?)+}#', $str, $matches);
$matches = array_map('stripBraces', $matches);
echo '<pre>'.print_r($matches, true);
// within array element 0...
// [0] => of what {I mean} will it ever be like this?
// [1] => text

 

Granted, simply using trim, this would leave inner nested braced words intact. A quick and dirty remedy to this would be to simply remove all instances of {} within the stripBraces function using strtr;

 

function stripBraces($arr){
    $trans = array('{' => '', '}' =>'');
    foreach($arr as &$val){
       $val = strtr($val, $trans);
    }
    return $arr;
}

 

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.