user188962
user188962

Reputation:

A little php help with this string formatting

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

Upvotes: 0

Views: 91

Answers (5)

Matteo Riva
Matteo Riva

Reputation: 25060

Generic solution not tied to a specific directory:

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

Upvotes: 0

John Parker
John Parker

Reputation: 54415

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.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382626

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;

Upvotes: 0

GZipp
GZipp

Reputation: 5416

$str = '/SV/temp_images/766321929_2.jpg';
list($numbers) = explode('_', basename($str));
echo $numbers;

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400922

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

Upvotes: 3

Related Questions