Jump to content
Sign in to follow this  
chronister2

Get text from last set of parentheses

Recommended Posts

Hello all. 

 

I hope everyone is doing well.

 

I would very much appreciate it if someone could help me figure this out. I am attempting to parse a list of over 600 items and I need to get the text in the last set of parentheses. 

$line = 'The First Tithe (the first tenth) of all our increase must be given to the Levites for their work in the sanctuary of God. (Numbers 18:21-26)';

preg_match('#\((.*?)\)#', $line, $match);

echo '<pre>'; print_r( $match ); echo '</pre>';

Returns 

Array
(
   [0] => (the first tenth)
   [1] => the first tenth
)

Whereas I wish it to return 

Array
(
 [0] => (Numbers 18:21-26)
 [1] => Numbers 18:21-26
)

How do I constrain this to find the final set. The part I am looking for is always at the end of the line.

 

 

Thank you in advance for any assistance you can provide.

 

Nate

 

 

 

Share this post


Link to post
Share on other sites

Well, preg_match_all() will give you all of the matches and you could just display the last one.

 

If the match is always at the end of the string, you could still use preg_match() and change your pattern to '#\((.*?)\)$#', where adding the '$' means the end of the line.

 

Or, a bit hacky, but you could strrev() the string, use preg_match() as you are and then strrev() the match to display it correctly.

Share this post


Link to post
Share on other sites

The preg_match_all did what I needed and I'm able to proceed.

 

The addition of the $ in the pattern did not yield any results at all (empty array returned) and I am not sure why.

 

I did not attempt the 3rd suggestion as that would have been a longer route to accomplish what I was looking for.

 

Thank you Sepodati, much appreciated.

Share this post


Link to post
Share on other sites

Personally I would fix the regex: don't let it match things that you don't want it to match.

#\(([\w\s]+ \d+:[\d:-]+)\)#
It may be enough that you can rely on it only matching verses and verse ranges but to be safe you could, you know, grab the last one it matched...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

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.