w3resource

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

PHP String: Exercise-22 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to remove trailing slash from a string.
Next: Write a PHP script to replace multiple characters from the following string.

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.