Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get Last Part of URL in PHP?
To get the last part of a URL in PHP, you can use several methods depending on your needs. The most common approaches are using basename(), pathinfo(), or regular expressions with preg_match().
Using basename()
The simplest method is using PHP's built-in basename() function, which extracts the filename from a path ?
<?php $websiteAddress = 'https://www.tutorialspoint.com/java/java_questions_answers/9989809898'; $lastPart = basename($websiteAddress); echo "The last part is: " . $lastPart; ?>
The last part is: 9989809898
Using pathinfo()
The pathinfo() function provides more detailed information about the URL path ?
<?php $websiteAddress = 'https://www.tutorialspoint.com/java/java_questions_answers/9989809898'; $pathInfo = pathinfo($websiteAddress); $lastPart = $pathInfo['basename']; echo "The last part is: " . $lastPart; ?>
The last part is: 9989809898
Using Regular Expressions
For more specific extraction (like only numbers), use preg_match() with a pattern ?
<?php
$websiteAddress = 'https://www.tutorialspoint.com/java/java_questions_answers/9989809898';
if(preg_match("/\/(\d+)$/", $websiteAddress, $matches)){
$lastResult = $matches[1];
echo "The result is: " . $lastResult;
} else {
echo "No numeric value found at the end";
}
?>
The result is: 9989809898
Using explode()
You can also split the URL by slashes and get the last element ?
<?php
$websiteAddress = 'https://www.tutorialspoint.com/java/java_questions_answers/9989809898';
$urlParts = explode('/', $websiteAddress);
$lastPart = end($urlParts);
echo "The last part is: " . $lastPart;
?>
The last part is: 9989809898
Comparison
| Method | Best For | Performance |
|---|---|---|
basename() |
Simple filename extraction | Fastest |
pathinfo() |
Detailed path information | Fast |
preg_match() |
Pattern-specific extraction | Slower |
explode() |
Array-based manipulation | Moderate |
Conclusion
Use basename() for simple cases, preg_match() for pattern-specific extraction, and explode() when you need to process multiple URL parts. Choose the method that best fits your specific requirements.
