tags:

views:

57

answers:

5

I have a string in this format:

    /SV/temp_images/766321929_2.jpg

Is there any small piece of code to get the numbers BEFORE the underscore, BUT AFTER temp_images/? In this case I want to get 766321929 only... ?

Thanks

+3  A: 

This should do the trick :

$str = '/SV/temp_images/766321929_2.jpg';
$m = array();
if (preg_match('#temp_images/(\d+)_#', $str, $m)) {
    echo $m[1];
}


The idea :

  • Use preg_match with a regular expression
    • that works with anything that begins with 'temp_images/'
    • and ends with '_'
    • but only returns the numbers (symbolized by \d) found between those
  • And the third parameter, $m, will contain what was matched :
    • $m[0] will be everything that was matched
    • $m[1] will be the first captured (between ()) part -- i.e. what you are looking for, here


And the output :

766321929


And if you're curious and what to know more about regex, don't hesitate to take a look at Regular Expressions (Perl-Compatible) -- there is a lot of interesting stuff to read, there ;-)

Pascal MARTIN
+1  A: 
$str = '/SV/temp_images/766321929_2.jpg';
list($numbers) = explode('_', basename($str));
echo $numbers;
GZipp
A: 

Here is a dirty way:

$contents = ' /SV/temp_images/766321929_2.jpg';
$contents = substr($contents, strpos($contents, 'temp_images/'));
$contents = substr($contents, strpos($contents, '/'));
$contents = substr($contents, 1);
$contents = substr($contents, 0, strpos($contents, '_'));
print $contents;
Sarfraz
A: 

You could use basename and then explode the resultant filename as such...

$fileComponents = explode('_', basename($filePathString));
$requiredComponent = $fileComponents[0];

That said, you'd need to add sanity checking, etc. as required.

middaparka
A: 

Generic solution not tied to a specific directory:

$name = preg_replace('/_.*/', '', basename($string));
kemp