0

Have a url kind of this

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

How to get product-123.html with regular expression?

I tried this:

echo 
preg_replace('#/([a-zA-Z0-9_-]+\.html)$#','$1','https://example.com.ua/part1/part2/part3/product-123.html');
Yrtymd
  • 433
  • 2
  • 5
  • 16
  • Possible duplicate of [Get Last Part of URL PHP](https://stackoverflow.com/questions/7395049/get-last-part-of-url-php) – revo Jul 23 '17 at 19:40

3 Answers3

5

You don't need regular expression for that

There's more than one way of doing it.

Look into 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.

That will get you most of the way there and will also separate the host for you. Then you just explode your way to the last part using explode() and 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
)

Or you can go straight to the point like this:

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

You can also just go a head and use explode() in combination of end() directly on the URL. (it's also a lot shorter if you don't need the extra information of parse_url)

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

You can also just use basename() like this

$url = "http://example.com/project/controller/action/param1/param2";
$last = basename($url);
// Output: param2
Patrick Simard
  • 2,294
  • 3
  • 24
  • 38
1

Why regex?

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

https://3v4l.org/rJiGL

Strrpos finds the last / and returns position.


Here is a preg_replace that will work if you must use regex.
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);
Andreas
  • 23,610
  • 6
  • 30
  • 62
1

The preg_replace only replaces what you have it find. In this case product-123.html. So you're replacing /product-123.html with product-123.html and the https://example.com.ua/part1/part2/part3 remains untouched.

To replace everything and only keep the match you'd do

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

you don't need a regex though to accomplish this task, and if you did it'd probably be cleaner to use preg_match.

Here's a preg_match approach:

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

Demo: https://3v4l.org/4o9RM

Regex demo: https://regex101.com/r/6dytu0/2/

chris85
  • 23,846
  • 7
  • 34
  • 51