0

I need to strip a URL using PHP to add a class to a link if it matches.

The URL would look like this:

http://domain.com/tag/tagname/

How can I strip the URL so I'm only left with "tagname"?

So basically it takes out the final "/" and the start "http://domain.com/tag/"

hakre
  • 193,403
  • 52
  • 435
  • 836
James
  • 1
  • Are you always looking to match the last thing enclosed in `/`s? Will there always be a final `/`? – Stephen Jul 30 '10 at 17:32

4 Answers4

2

For your URL

http://domain.com/tag/tagname/

The PHP function to get "tagname" is called basename():

echo basename('http://domain.com/tag/tagname/');   # tagname
hakre
  • 193,403
  • 52
  • 435
  • 836
0

combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.

Scott M.
  • 7,313
  • 30
  • 39
0

As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:

<?php 
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>

(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)

And as an alternate to that, you could also use preg_match_all:

<?php 
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Stephen
  • 6,027
  • 4
  • 37
  • 55
0

Many thanks to all, this code works for me:

$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
CoolBeans
  • 20,654
  • 10
  • 86
  • 101