xProteuSx Posted April 25, 2012 Share Posted April 25, 2012 I have a really weird thing that I have to do, and I can't figure it out. I've tried about 1 million nested loops, and just can't get this to work. What I need to do is get the longest number from a string. So, for example, take the following: $string = "asdfasd234kjljlkjlj34659823423sadfasdadasdfasdfasd3242sdasddsda2"; function getNumber($a) { //do something with $string and return the longest number from it } so that ... echo getNumber($string); will return '34659823423' Thanks in advance, fellas! I've really been racking my brain there. Quote Link to comment https://forums.phpfreaks.com/topic/261562-get-the-longest-number-from-a-string/ Share on other sites More sharing options...
QuickOldCar Posted April 25, 2012 Share Posted April 25, 2012 This works. <?php $string = "asdfasd234kjljlkjlj34659823423sadfasdadasdfasdfas d3242sdasddsda2"; function highestNumber($string){ $numbers = preg_replace("/[^0-9]/", ' ',$string); return max(explode(" ",trim($numbers))); } echo highestNumber($string); ?> Quote Link to comment https://forums.phpfreaks.com/topic/261562-get-the-longest-number-from-a-string/#findComment-1340324 Share on other sites More sharing options...
xProteuSx Posted April 25, 2012 Author Share Posted April 25, 2012 I've always had a hard time with this regex stuff! Thank you SO VERY MUCH for your help. I can't believe that its a 2 line function. I'm a little embarassed ... Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/261562-get-the-longest-number-from-a-string/#findComment-1340325 Share on other sites More sharing options...
QuickOldCar Posted April 25, 2012 Share Posted April 25, 2012 well this would get the highest, but you mentioned longest, also i forgot the decimal in the regex, so can add it to the other if the highest is fine for you. anyway, here is to find the longest, just one of many ways. <?php $string = "asdfasd234.987654324567kjljlkjlj34659823423sadfasdadasdfasdfas d3242sdasddsda2"; function longestNumber($string){ $numbers = preg_replace("/[^0-9.]/", ' ',$string); $num_array = explode(" ",trim($numbers)); $longest = ''; foreach($num_array as $number){ if(strlen($number) > strlen($longest)){ $longest = $number; } } return $longest; } echo longestNumber($string); ?> Quote Link to comment https://forums.phpfreaks.com/topic/261562-get-the-longest-number-from-a-string/#findComment-1340326 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.