-1

I need to get second last word of a url which is split by "/".I have tried

$refer_split = explode("/", $refer);
    echo $refer_split[6]; 

but it is not working in case of small urls. please suggest a good way to find the secondlast word in php

daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
Nighina t t
  • 140
  • 1
  • 4
  • 15
  • Count the number of array entries, and do some most basic math? – CBroe Jun 20 '17 at 08:11
  • `echo $refer_split[count($refer_split)-2];` – apokryfos Jun 20 '17 at 08:12
  • Possible duplicate of [How to get string before last slash and after second last slash in URL](https://stackoverflow.com/questions/20823748/how-to-get-string-before-last-slash-and-after-second-last-slash-in-url) – Yadhu Babu Jun 20 '17 at 08:16
  • In codeigniter you can use the uri segments() https://www.codeigniter.com/user_guide/libraries/uri.html –  Jun 20 '17 at 09:38

3 Answers3

6

use CI Built in Functions

$url_count=$this->uri->total_segments();
echo  $this->uri->segment($url_count-1);

-1 is used because $this->uri->total_segments() this give you the last word and -1 will give second last

Reuben Gomes
  • 878
  • 9
  • 16
0

Try following :

$refer = "https://meta.stackexchange.com/questions/190344/replacing-urls-with-dummy-urls";
$refer_split = explode("/", $refer);
echo (count($refer_split) > 1) ? $refer_split[ count($refer_split) - 2] : 'no parts available'; 
// echo's '190344'

DEMO

daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
0

You can do something like this:

$split = explode("/", $refer);
$count = count($split);
if($count > 1){
    echo $split[$count - 2];
}

This code won't work if your url count is 1, because you'd be trying to access element -1 which won't exist.

Florian Humblot
  • 1,121
  • 11
  • 29