个人资料如何获取 url 的最后一部分

pcre. How to get last part of url

有url种这种

https://example.com.ua/part1/part2/part3/product-123.html 

如何用正则表达式得到product-123.html

我试过这个:

echo 
preg_replace('#/([a-zA-Z0-9_-]+\.html)$#','','https://example.com.ua/part1/part2/part3/product-123.html');

你不需要正则表达式

实现它的方法不止一种。

调查parse_url()

parse_url(): This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

这将使您完成大部分工作,并且还会为您分离主机。然后你只需使用 explode() 和 end() 爆炸到最后一部分。

$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['last'] = end(explode('/', $url[path]));

Array
(
    [scheme] => http
    [host] => example.com
    [path] => /project/controller/action/param1/param2
    [last] => param2
)

或者你可以这样直奔主题:

$last = ltrim(strrchr(parse_url($url, PHP_URL_PATH), '/'), '/');

您也可以直接在 URL 上使用 explode() 和 end() 的组合。 (如果你不需要parse_url的额外信息,它也会短很多)

$last = end(explode('/', $url));

您也可以像这样使用 basename()

$url = "http://example.com/project/controller/action/param1/param2";
$last = basename($url);
// Output: param2

为什么要使用正则表达式?

$str ="https://example.com.ua/part1/part2/part3/product-123.html";
Echo Substr($str, strrpos($str, "/")+1);

https://3v4l.org/rJiGL

Strrpos 找到最后的 / 和 returns 位置。


如果您必须使用正则表达式,这里有一个 preg_replace 可以使用。
https://regex101.com/r/6zJwBo/1

$re = '/.*\//';
$str = 'https://example.com.ua/part1/part2/part3/product-123.html';
$subst = '';

$result = preg_replace($re, $subst, $str);

preg_replace 仅替换您找到的内容。在这种情况下 product-123.html。因此,您将 /product-123.html 替换为 product-123.html 并且 https://example.com.ua/part1/part2/part3 保持不变。

要替换所有内容并只保留您想要的匹配项

echo 
preg_replace('#.*/([a-zA-Z0-9_-]+\.html)$#','','https://example.com.ua/part1/part2/part3/product-123.html');

你不需要正则表达式来完成这个任务,如果你这样做了,使用 preg_match.

可能会更干净

这是一个 preg_match 方法:

preg_match('#[a-zA-Z0-9_-]+\.html$#', 'https://example.com.ua/part1/part2/part3/product-123.html', $match);
echo $match[0];

演示:https://3v4l.org/4o9RM

正则表达式演示:https://regex101.com/r/6dytu0/2/