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,892
  • 8
  • 43
  • 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,366
  • 2
  • 27
  • 53
4

Regular expression solution.

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

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

Demo

chanchal118
  • 3,551
  • 2
  • 26
  • 52
1

Using capturing group, $:

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

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

So basename() does exactly that.

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