4

If I have a URL look like this:

http://wwww.example/test1/test2/test3/

How can I retrieve string test3 from the url above?

Felix
  • 37,443
  • 7
  • 40
  • 55

4 Answers4

8
$str = explode("/","http://wwww.example/test1/test2/test3/");
echo $str[count($str)-2];

DEMO: https://eval.in/83914

Awlad Liton
  • 9,260
  • 2
  • 26
  • 50
4

Regular expression solution.

$url = 'http://wwww.example/test1/test2/test3/';

preg_match('#.*/(.*)/$#', $url, $matches);
echo $matches[1];

Demo

chanchal118
  • 3,339
  • 2
  • 25
  • 50
1

Using capturing group, $:

preg_match('!/([^/]+)/[^/]*$!', 'http://wwww.example/test1/test2/test3/', $matches);
echo $matches[1];

DEMO: http://ideone.com/7EVfZa

falsetru
  • 336,967
  • 57
  • 673
  • 597
0

So basename() does exactly that.

$url = 'http://www.example/test1/test2/test3/';
echo basename($url); // returns : test3;
JSG
  • 330
  • 4
  • 12