chronister2 Posted August 30, 2017 Share Posted August 30, 2017 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 Quote Link to comment https://forums.phpfreaks.com/topic/304806-get-text-from-last-set-of-parentheses/ Share on other sites More sharing options...
Solution Sepodati Posted August 30, 2017 Solution Share Posted August 30, 2017 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. Quote Link to comment https://forums.phpfreaks.com/topic/304806-get-text-from-last-set-of-parentheses/#findComment-1550421 Share on other sites More sharing options...
chronister2 Posted August 30, 2017 Author Share Posted August 30, 2017 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. Quote Link to comment https://forums.phpfreaks.com/topic/304806-get-text-from-last-set-of-parentheses/#findComment-1550432 Share on other sites More sharing options...
requinix Posted August 30, 2017 Share Posted August 30, 2017 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... Quote Link to comment https://forums.phpfreaks.com/topic/304806-get-text-from-last-set-of-parentheses/#findComment-1550447 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.