简体   繁体   中英

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 , and 66_99U is a random value

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 .

You can use \\K here to makei more thorough.

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

See demo.

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

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 :

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

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.

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