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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.