Jump to content

Get the Longest Number from a String


xProteuSx

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/261562-get-the-longest-number-from-a-string/
Share on other sites

This works.

 

<?php
$string = "asdfasd234kjljlkjlj34659823423sadfasdadasdfasdfas d3242sdasddsda2";

function highestNumber($string){
    $numbers = preg_replace("/[^0-9]/", ' ',$string);
    return max(explode(" ",trim($numbers)));
}

echo highestNumber($string);
?>

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);
?>

Archived

This topic is now archived and is closed to further replies.

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