最后一次斜线后的文字,我的错误是什么?

I want to get out of the URL after the last slash "/" the text. The page URL is very variable, for example:

http://mydomain.com/colors/productname.html (result is "productname") OK!

http://mydomain.com/colors/size/zip/shipment/ (result is "shipment") OK!

or

http://mydomain.com/colors/ (result is "null") Null!

It works well so far except for the last example. Once, just a slash "/" after the domain name is I get no result.

What is my mistake?

Thanks in advance!

$url = "variable"       
if (strpos($url,'.h') !== false) {
$url = preg_replace('/\.h.*/', '/', $url);}
$url = rtrim($url, "/");
$str = substr(strrchr($url, '/'), 1);
$str = str_replace('-',' ',$str);
$keys = str_replace('/ /', '%20', $str);
$metric = urlencode($keys);

php already has a function that does this its called basename

$url = "http://mydomain.com/colors/";
echo basename($url);

//outputs 
colors

$url = "http://mydomain.com/colors/productname.html";
echo basename($url);

//outputs 
productname.html

What is stopping you from using basename?

<?php
  $url  = "http://mydomain.com/colors/";
  $url  = basename( $url ); //outputs "colors"
  echo $url;
?>

Or if you dont want the ".html" in output, you can use pathinfo with PATHINFO_FILENAME flag

<?php
  $url  = "http://mydomain.com/colors.html";
  $url  = pathinfo( $url, PATHINFO_FILENAME ); //also outputs "colors"
  echo $url;
?>