Jump to content

Get text from last set of parentheses


Go to solution Solved by Sepodati,

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

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/304806-get-text-from-last-set-of-parentheses/
Share on other sites

  • Solution

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.

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.

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