Jump to content

Help with greedy(?) expression


markroy

Recommended Posts

Hi;

 

I'm trying to extract the 'options' from a string in this form:

 

    {options=opt_1|opt_2|opt_3|opt_n}

 

Here's my code:

    $string = '{options=opt_1|opt_2|opt_3|opt_n}';  
    $regex = '~{options=([^\|]*)(?:\|([^\|]*))*?}~';
    preg_match_all( $regex, $string, $matches );
    print_r($matches);

 

However, for matches, I only get "opt_1" and "opt_n". "opt_2" and "opt_3" are missing. I thought it had something to do with greedy-ness, but still can't make it work.

 

Can someone show me where I've gone wrong?

 

TIA

Mark

Link to comment
Share on other sites

Use this

 

<?php
$string = '{options=opt_1|opt_2|opt_3|opt_n}'; 
$regex = '~{options=(.*?)}~';
preg_match_all( $regex, $string, $matches );
$matches = $matches[1];

$M = array();

foreach ($matches as $k=>$v)
{
$Ma = preg_split('~\|~', $v);
$M[] = $Ma;
}

print_r($M);

?>

Link to comment
Share on other sites

Faster to use explode():

 

<?php
$str = '{options=opt_1|opt_2|opt_3|opt_n}';
preg_match('~{options=([^}]+)}~i', $str, $match);
$options = explode('|', $match[1]);
echo '<pre>' . print_r($options, true) . '</pre>';
?>

 

Alternatively:

 

$str = '{options=opt_1|opt_2|opt_3|opt_n}';
$arr = preg_split('#(?:{options=)?([^|}]+)[|}]#', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>'.print_r($arr, true);

 

Granted, explode (and other built-in PHP functionality) is indeed faster.. this is just another way in splitting that particular example string (read - splitting a string using that particular format). As a result, this of course assumes that the string isn't some random string like 'blah|blah2|blah3' (in otherwords, strings that miss the {option= bit) or even worse, a string that doesn't contain {option= but contains something else like {someOtherOptions=blah|blah2|blah3} , which would still be parsed in this case (which, depending on the string, might not give desired / accurate results). Again, just another way if the circumstances are right (perhaps a big 'if' though).

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.