I have a url, - " http://example.com/sales/view/id/705
" and I need get a last segment (705).
How can I do this using PCRE?
This should do it in Perl:
my ($last) = $url =~ /([^\/]+)\z/;
But I would rather use the URI
module:
my $last = (URI->new($url)->path_segments)[-1];
(In PHP) I would not use PCRE for such a trivial and un-ambiguous job. 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:
$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:
$url = 'http://example.com/sales/view/id/705';
substr($url, strrpos($url, '/') + 1);
Non PCRE alternative:
$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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.