-3

I wanted to print the last characters after "/" in a url. but instead it is printing the whole url, I expected the output to be just "index.php" instead it is printing out the whole url.

How should i go about doing it right?

 $data = $_SERVER['REQUEST_URI'];
    $whatIWant = substr($data, strpos($data, "/") + 1); 
     echo $whatIWant;

You can see it here

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
Ibrahim
  • 11
  • 6

6 Answers6

1

You should get the actual link by

<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$getpath=explode("/",$actual_link);
echo end($getpath);
?>

Short Explanation :

Step 1 : Get the url by

http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]

Step 2 : Explode with slash

explode("/",$actual_link)

Step 3 : Get the last part

end($getpath);
Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
0

Try this..

<?php
$data = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$whatIWant = explode("/",$data);
 echo end($whatIWant);?>
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
  • @Jocker *it is help ful means accept my answer* NO! This doesn't mean that OP has to accept exactly your answer. Maybe an upV because that's what the tooltip says: *This answer is useful*; There is a good post on meta how accepting works and which may helps OP to decide which answer he can/should choose/accept: http://meta.stackexchange.com/q/5234 – Rizier123 Apr 10 '15 at 09:32
0

You can also try it this way using strrchr :

$url = 'http://spiritofethiopia.com/test/test/test/index.php';
$str = substr(strrchr($url, '/'), 1);
echo $str;

strrchr — Find the last occurrence of a character in a string.

Jenis Patel
  • 1,617
  • 1
  • 13
  • 20
0

Try This:

working solution,

<?php 

  $url = 'http://test/test/test/index.php';
  $tokens = explode('/', $url);
  echo $tokens[sizeof($tokens)-1];

?>
Madhu
  • 2,643
  • 6
  • 19
  • 34
0

You can use preg_match whith a correct RegExp to capture the end of the URL.

<?php
$data = $_SERVER['REQUEST_URI'];

if(preg_match('#/([^/]*?)$#', $data, $matches) == 1) {
    echo $matches[1];
}
else {
    // Should not happen
    /*
     * Throw exception
     */
}

?>

Med
  • 2,035
  • 20
  • 31
0

Try strripos instead of strpos, it may works

<?php
    $data = $_SERVER['REQUEST_URI'];
    $whatIWant = substr($data, strripos($data, "/") + 1); 
        echo $whatIWant;
    ?>
fba_pereira
  • 196
  • 2
  • 12