Page 1 of 1

select string from round bracket

Posted: Fri Oct 14, 2011 12:41 am
by rahulsonar
Hi All,

I have a pattern like this:

RS-1.75 m(TE)

from which, I want to select string from round brackets ( in this case, TE). Can anyone help me in regex or any other way to do this?

Thanks,

Re: select string from round bracket

Posted: Mon Oct 17, 2011 6:12 pm
by ouchiko

Code: Select all

$string = "This is a (IE) test about the this (UY)";
preg_match_all("/\((.*)\)/U",$string,$results);


foreach ($results[1] as $ID ) print $ID . "<BR>";

Re: select string from round bracket

Posted: Wed Dec 28, 2011 4:36 pm
by Tosha
Thank you for this response. I had the very same question. This looks like it would work, but I am a little confused about the /U modifier. It seems that this would cause some problems, I might be wrong about this. Is there another approach that I can take in this situation, or is this the best way? I will need to work this issue out before I can move forward on the human resource management software that I have under development. As of now, this little snippet is causing bugs all over the place, so hopefully someone has some helpful advice. Thank you.

Re: select string from round bracket

Posted: Wed Dec 28, 2011 4:57 pm
by ragax
Yes, ouchiko's pattern works, but...
I would not recommend it.
Why? Because it uses an uncommon (and potentially confusing) modifier: /U
This pattern modifier says "swap the greediness status of the star and question mark quantifiers". So in this expression, the "greedy star" is lazy!!! That means you have a non-standard regex that will break almost everywhere except in this particular context.

Making only slight modifications to ouchiko's code, I would suggest something much more conventional:

Code: Select all

<?php 
$string = "This is a (IE) test about the this (UY)";
preg_match_all(",\(([^)]*)\),",$string,$results);
foreach ($results[1] as $ID ) print $ID . "<br />";
?>
In the capturing parentheses, instead of capturing everything, we capture anything that is not a closing parenthesis.

Note: This is only a starting point on the wide topic of capturing the content inside parentheses. For nested sets of parentheses, you may have to use a recursive regex.

Wishing you all a beautiful end of the year.