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
How to get the Last n Characters of a PHP String
In PHP, you can extract the last n characters of a string using the substr() function with a negative start position. This approach counts from the end of the string backwards.
Using substr() Function
The substr() function extracts a portion of a string based on the starting position and optional length. To get the last n characters, use a negative starting position.
Syntax
substr(string $string, int $start, ?int $length = null): string|false
Parameters:
$stringThe input string from which to extract characters$startStarting position (negative values count from the end)$lengthOptional length of substring to extract
Example
Here's how to get the last 6 characters of a string ?
<?php $string = "Hello, World!"; $n = 6; // Number of characters to extract from the end $lastNCharacters = substr($string, -$n); echo $lastNCharacters; ?>
World!
Using substr() with strlen()
Alternative approach using strlen() to calculate the starting position ?
<?php $string = "Programming"; $n = 4; $startPosition = strlen($string) - $n; $lastNCharacters = substr($string, $startPosition); echo $lastNCharacters; ?>
ming
Multiple Examples
Different string lengths and character counts ?
<?php
$examples = [
"TutorialsPoint" => 5,
"PHP" => 2,
"WebDevelopment" => 7
];
foreach($examples as $string => $n) {
$result = substr($string, -$n);
echo "Last $n chars of '$string': $result<br>";
}
?>
Last 5 chars of 'TutorialsPoint': Point Last 2 chars of 'PHP': HP Last 7 chars of 'WebDevelopment': opment
Conclusion
The substr() function with negative start position is the most efficient way to extract the last n characters from a PHP string. This method is simple, readable, and works consistently across different string lengths.
