简体   繁体   English

正则表达式获取最后一个URL

[英]Regex For Get Last URL

I have: 我有:

stackoverflow.com/.../link/Eee_666/9_uUU/66_99U

What regex for /Eee_666/9_uUU/66_99U ? /Eee_666/9_uUU/66_99U正则表达式是什么?

Eee_666 , 9_uUU , and 66_99U is a random value Eee_6669_uUU66_99U是一个随机值

How can I solve it? 我该如何解决?

As simple as that: 就如此容易:

$link = "stackoverflow.com/.../link/Eee_666/9_uUU/66_99U";
$regex = '~link/([^/]+)/([^/]+)/([^/]+)~';
# captures anything that is not a / in three different groups
preg_match_all($regex, $link, $matches);
print_r($matches);

Be aware though that it eats up any character expect the / (including newlines), so you either want to exclude other characters as well or feed the engine only strings with your format. 请注意,虽然它会占用期望/ (包括换行符)的任何字符,因此您要么也要排除其他字符,要么仅使用您的格式为引擎提供字符串。
See a demo on regex101.com . 请参阅regex101.com上的演示

You can use \\K here to makei more thorough. 你可以在这里使用\\K来使我更彻底。

stackoverflow\.com/.*?/link/\K([^/\s]+)/([^/\s]+)/([^/\s]+)

See demo. 见演示。

https://regex101.com/r/jC8mZ4/2 https://regex101.com/r/jC8mZ4/2

In the case you don't how the length of the String: 在你没有如何长度的情况下:

$string = stackoverflow.com/.../link/Eee_666/9_uUU/66_99U

$regexp = ([^\\/]+$)

result: group1 = 66_99U 结果: group1 = 66_99U

be careful it may also capture the end line caracter 小心它也可能捕获终点线

For this kind of requirement, it's simpler to use preg_split combined with array_slice : 对于这种要求,使用preg_splitarray_slice结合使用更简单:

$url = 'stackoverflow.com/.../link/Eee_666/9_uUU/66_99U';
$elem = array_slice(preg_split('~/~', $url), -3);
print_r($elem);

Output: 输出:

Array
(
    [0] => Eee_666
    [1] => 9_uUU
    [2] => 66_99U
)

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

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