[英]How get last segment of url using PCRE?
I have a url, - " http://example.com/sales/view/id/705
" and I need get a last segment (705). 我有一个网址-“ http://example.com/sales/view/id/705
”,我需要获取最后一段(705)。
How can I do this using PCRE? 如何使用PCRE执行此操作?
(In PHP) I would not use PCRE for such a trivial and un-ambiguous job. (在PHP中)我不会将PCRE用于如此琐碎而明确的工作。 I would just do: 我会做:
$parts = explode('/', rtrim($url, '/'));
$partYouWant = array_pop($parts);
EDIT 编辑
If you need to use PCRE (although I don't know why you would) this variation on eugene y's answer would do it: 如果您需要使用PCRE(尽管我不知道为什么会这样),那么对eugene y的这种回答就可以做到:
$pattern = '#/([^/]+)\z#';
$url = 'http://example.com/sales/view/id/705';
preg_match($pattern, $url, $matches);
echo $matches[1];
In PHP you can do this in a single line code: 在PHP中,您可以在一行代码中执行此操作:
$url = 'http://example.com/sales/view/id/705';
substr($url, strrpos($url, '/') + 1);
Non PCRE alternative: 非PCRE替代方案:
$url="http://example.com/sales/view/id/705";
$lastPart = current(array_reverse((explode('/',parse_url($url,PHP_URL_PATH)))));
Doubt if it's any faster though 怀疑是否更快
You could use this pattern ([^\\/]*)$
for everything from last /
to end. 您可以使用([^\\/]*)$
来处理从最后/
到结尾的所有内容。
Maybe also interesting: ([^\\/\\?]*)(\\?.*)?$
gives you everything between last /
and first ?
也许还很有趣: ([^\\/\\?]*)(\\?.*)?$
提供了最后/
和第一个之间的所有内容?
如果可以,请对PCRE拒绝:-)。
echo basename('http://example.com/sales/view/id/705');
Simplest: 最简单的:
$ok=preg_match('#\d+$#',$url,$m);
if($ok)
echo $m[0],"\n";
Brainy: 聪明:
$ok=preg_match('#/(\d+)$#',$url,$m);
if($ok)
echo $m[1],"\n";
Flexible: (as it also allows words, other than digits) 灵活:(因为它还允许数字以外的单词)
$ok=preg_match('#/(\w+)$#',$url,$m);
if($ok)
echo $m[1],"\n";
More flexible: (as it now allows everything that's not a / to match) 更加灵活:(因为它现在允许所有非/匹配的内容)
$ok=preg_match('#/(.*?)$#',$url,$m);
if($ok)
echo $m[1],"\n";
preg_match('@/([1-9]\d*)/?(?:$|\?)@', $url, $matches);//$matches[1] contains your id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.