Quick Regex php - getting ID from a string
As anyone who's seen my posts will know, I'm a regex pleb. Anyone can tell me how to get the ID from this file name, would be very grateful?
/data/64786/sasf.zip
开发者_Go百科I need the 64786 bit from this line, always follows /data/ - anyone able to help quickly?
~/data/(\d+)/~
This will match a sequence of decimals (0-9) immediately following the string /data/
. Match is in group 1
.
If the string can also look like /data/64786
(i.e., nothing after the number), use ~/data/(\d+)~
instead. Actually, you can use this either way since \d+
will be greedy per default and thus match as many decimals as possible. (Tested at Rubular.)
This is a number. Use the \d+
placeholder for decimals:
preg_match("#(\d+)#", $str, $matches);
$id = $matches[1];
If the id always occurs at the same place, then you can add the slashes #/(\d+)/#
for reliability. Most text strings can be used as-is in regular expressions as anchors.
[reference, tools] https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world
You could grab the ID using the following code:
$filename = '/data/64786/sasf.zip';
$prefix = '/data/';
$prefix_pos = strpos($filename, $prefix);
if($prefix_pos !== false)
{
$prefix_pos_end = $prefix_pos + strlen($prefix);
$slash_pos = strpos($filename, '/', $prefix_pos_end);
$id = substr($filename, $prefix_pos_end, $slash_pos - $prefix_pos_end);
}
else $id = false;
Why don't you try: basename(dirname("/data/64786/sasf.zip"))
精彩评论