Jump to content

[SOLVED] function to grab number out of a string


dadamssg

Recommended Posts

I'm attaching images to events. And im going to name the events the timestamp that they end at and then attach the creators login name. So an example would be

 

324559823759admin.png

 

I know that "timestamp" probably isn't legit but...i need a function that will grab all those beginning numbers up until it hits a letter...so the function would return "324559823759" in this case if "324559823759admin.png" was inputted. I have no clue how to do this...does anybody???

Link to comment
Share on other sites

There are numerous ways to skin this cat I'd wager.. two possible solutions could be:

 

Example 1:

function grabNumbers($str){
    preg_match('#^\d+#', $str, $match);
    return $match[0];
}

$file = '324559823759admin.png';
echo grabNumbers($file); // Output: 324559823759

 

Exmaple 2 (using a possible non-regex solution):

function grabNumbers($str){
    list($number,$string) = sscanf($str, "%d%s"); // if using a 64-bit system simply return $number - otherwise,
    return str_replace($string, '', $str); // we remove string from filename instead 
}

$file = '324559823759admin.png';
echo grabNumbers($file); // Output: 324559823759

Link to comment
Share on other sites

i just tried both of these with no luck...

 

function grabNumbers($str){
    preg_match('#^\d+#', $str, $match);
    return $match[0];
}

$file = '324559823759admin235.png';
echo grabNumbers($file); // Output: 324559823759

function grabNumberss($str){
    list($number,$string) = sscanf($str, "%d%s"); // if using a 64-bit system simply return $number - otherwise,
    return str_replace($string, '', $str); // we remove string from filename instead 
}

$file = '324559823759admin3465.png';
echo grabNumberss($file); // Output: 324559823759

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.