Number from a string

A

Anonymous

Guest
Hi everyone,
I have a small problem with part of my script, basically I have a string which contains an address for an image say: http://www.wherever.com/images/blahblah0322.jpg
The address, number length & extension will be different every time and what I need is to return the variable $number from an image address which will be "0322" in the case of the example.
I search the manual in the hope of finding a str_getlastnumberfromanimageaddress() function but couldn’t find one :)
Any suggestions gratefully received.
 
Good question. Well, first what you need to do is strip away everything except the filename. Use parse_url() andexplode() to do this. Then, strip away everything before the dot using explode(). Then, iterate backwards through the remaining filename until you find the first number (using is_numeric()) from the end. Then you'll have the index of the first number, so you can use substr() to extract it. Something like this:

Code:
<?php
$url = 'http://www.wherever.com/images/blahblah0322.jpg';
$url_parsed = parse_url($url); // get the path part
$path_exploded = explode('/', $url_parsed['path']);
$filename = $path_exploded[count($path_exploded) - 1]; // get everything after the last slash

$filename_exploded = explode('.', $filename);
$filename = $filename_exploded[0]; // strip off the extension

$filename_len = strlen($filename);

$first_number = $filename_len;

// iterate backward through $filename
for($i = $filename_len - 1; $i >= 0; $i--) {
   // check if each character is numeric
   if(!is_numeric($filename{$i})) {
      $first_number = $i + 1;
      break;
   }
}

if($first_number != $filename_len) {
   // extract the number from the filename
   $number = substr($filename, $first_number);
   echo $number;
} else {
   echo 'something went wrong (number not found)!';
}

?>

That ought to work, but it's completely untested, so happy bug-hunting!
 
yK said:
works perfectly :D thanks!

Really? I'm amazed!

Anyway, you'd do well to encapsulate that in a function. Also, it occurred to me a bit later that you could probably do the same thing using regular expressions in about 2 lines of code, but since I suck with regex, I couldn't tell you how. :)
 
Back
Top