Delete all characters to last / in url

I need to delete all characters to the last "/"

This is my url:

http://www.example.com/highlights/cat/all-about-clothing/

And I want to have only:

all-about-clothing

thanks

+4
source share
7 answers

Use basename ()

$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
echo basename($str);
// Outputs: all-about-clothing

EDIT:

Another solution:

$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$path = pathinfo($str, PATHINFO_BASENAME);
echo "<br/>" . $path;
+7
source

Use the PHP function parse_url () .

edit: basename()or pathinfo()is an easier way.

+2
source
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$str = trim($str,'/');
$str = explode('/',$str);
echo $str = end($str);

//

-

+1
<?php
$url = "http://www.example.com/highlights/cat/all-about-clothing/";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
echo $basename;
?>
0

regex:

$match = [];
$subject = 'http://www.example.com/highlights/cat/all-about-clothing/';
$pattern = '/http:\/\/www\.example\.com\/highlights\/cat\/(.*)/';
preg_match($pattern, $subject, $match);
print_r($match);

.

0
<?php
$url = 'http://www.example.com/highlights/cat/all-about-clothing/';
$basename =  split('/',$url);    
echo $basename[5];
?>
0

URL- , , , , :

http://www.example.com/highlights/cat/all-about-clothing/?page=1 http://www.example.com/highlights/cat/all-about-clothing/item/1

to cache the third โ€œdirectoryโ€ after the domain name and ignore the rest of the URL, you can use the following code:

$url = "http://www.example.com/highlights/cat/all-about-clothing/item/1";

$url_path = parse_url($url, PHP_URL_PATH); #  /highlights/cat/all-about-clothing/item/1

$dirs = explode('/', $url_path); # Array([0] =>"", [1]=>"highlights", [2]=>"cat", [3]=>"all-about-clothing", [4]=>"item", [5]=>"1") 

echo $dirs[3]; # all-about-clothing
0
source

Source: https://habr.com/ru/post/1614264/


All Articles