简体   繁体   English

Quick Regex php - 从字符串中获取ID

[英]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? 任何人都可以告诉我如何从这个文件名中获取ID,会非常感激吗?

/data/64786/sasf.zip

I need the 64786 bit from this line, always follows /data/ - anyone able to help quickly? 我需要来自这一行的64786位,总是跟随/ data / - 任何人都可以快速帮助?

~/data/(\d+)/~

This will match a sequence of decimals (0-9) immediately following the string /data/ . 这将匹配字符串/data/后面的一系列小数(0-9)。 Match is in group 1 . 比赛在第1组。

If the string can also look like /data/64786 (ie, nothing after the number), use ~/data/(\\d+)~ instead. 如果字符串也可以看起来像/data/64786 (即数字之后没有任何内容),请改用~/data/(\\d+)~ Actually, you can use this either way since \\d+ will be greedy per default and thus match as many decimals as possible. 实际上,你可以使用这种方式,因为\\d+默认是贪心的,因此匹配尽可能多的小数。 ( Tested at Rubular .) 在Rubular测试过 。)

This is a number. 这是一个数字。 Use the \\d+ placeholder for d ecimals: 使用\\d+占位符表示d ecimals:

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. 如果id总是出现在同一个地方,那么你可以为可靠性添加斜杠#/(\\d+)/# 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 [参考,工具] https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world

You could grab the ID using the following code: 您可以使用以下代码获取ID:

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

你为什么不试试: basenamedirname (“/ data / 64786 / sasf.zip”))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM