Reputation:
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
Reputation: 25060
Generic solution not tied to a specific directory:
$name = preg_replace('/_.*/', '', basename($string));
Upvotes: 0
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
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
Reputation: 5416
$str = '/SV/temp_images/766321929_2.jpg';
list($numbers) = explode('_', basename($str));
echo $numbers;
Upvotes: 1
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 :
preg_match
with a regular expression
temp_images/
'_
'\d
) found between those$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