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:

  • $string The input string from which to extract characters

  • $start Starting position (negative values count from the end)

  • $length Optional 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.

Updated on: 2026-03-15T10:28:48+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements