Monday, May 25, 2026
HomeLanguagesHow to get the last n characters of a PHP string?

How to get the last n characters of a PHP string?

Write a PHP program to get last n characters of a given string.

Examples:

Input : $str = "neveropen!"
        $n = 6 
Output : Geeks!

Input : $str = "neveropen!"
        $n = 9
Output : forGeeks!

Method 1: Tn this method, traverse the last N characters of the string and keep appending them in a new string.

Example:




<?php
  
$str = "neveropen!";
$n = 6;
  
// Starting index of the string
// where the new string begins
$start = strlen($str) - $n;
  
// New string
$str1 = '';
  
for ($x = $start; $x < strlen($str); $x++) {
      
    // Appending characters to the new string
    $str1 .= $str[$x];
}
  
// Print new string
echo $str1;
?>


Output:

Geeks!

Method 2: Another way to do this use inbuilt library function substr with parameters as the name of the string.

Example:




<?php
  
$str = "neveropen!";
$n = 6;
  
$start = strlen($str) - $n;
  
// substr returns the new string.
$str1 = substr($str, $start);
  
echo $str1;
?>


Output:

Geeks!

Note: In above example, $start can also take -N to create a sub-string of last n characters

RELATED ARTICLES

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS