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
https://forums.phpfreaks.com/topic/174362-help-with-greedy-expression/
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);

?>

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).

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.