w3resource

PHP String Exercises: Get the characters after the last '/' in an url


22. Get Characters After Last '/' in URL

Write a PHP script to get the characters after the last '/' in an url.

Sample URL : 'http://www.example.com/5478631'

Visual Presentation:

PHP String Exercises: Get the characters after the last '/' in an url

Sample Solution:

PHP Code:

<?php
$my_url = 'http://www.example.com/5478631';
// Define the URL string.

echo substr($my_url, strrpos($my_url, '/' )+1)."\n";
// Extract the portion of the URL after the last occurrence of '/' and output it.
?>

Output:

5478631

Explanation:

The above PHP code snippet extracts the portion of a URL after the last occurrence of the forward slash '/'.

  • strrpos($my_url, '/') finds the position of the last occurrence of '/' in the URL string $my_url.
  • substr($my_url, strrpos($my_url, '/') + 1) extracts the substring starting from the position after the last slash to the end of the string.
  • Finally, it echoes out the extracted portion, which in this case is '5478631', representing the end part of the URL.

Flowchart :

Flowchart: Get the characters after the last '/' in an url

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract the substring after the last '/' character in a given URL using strrpos() and substr().
  • Write a PHP function to parse a URL and return the last segment, even if the URL ends with a slash.
  • Write a PHP program to split a URL by the '/' delimiter and output the final segment as the unique identifier.
  • Write a PHP script to determine if a URL contains query parameters and extract only the path component following the last slash.

Go to:


PREV : Remove Trailing Slash from a String.
NEXT : Replace Multiple Characters in a String.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.