How to get the last n characters of a PHP string?
Last Updated :
31 Oct, 2018
Write a PHP program to get last n characters of a given string.
Examples:
Input : $str = "GeeksforGeeks!"
$n = 6
Output : Geeks!
Input : $str = "GeeksforGeeks!"
$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 = "GeeksforGeeks!" ;
$n = 6;
$start = strlen ( $str ) - $n ;
$str1 = '' ;
for ( $x = $start ; $x < strlen ( $str ); $x ++) {
$str1 .= $str [ $x ];
}
echo $str1 ;
?>
|
Method 2: Another way to do this use inbuilt library function substr with parameters as the name of the string.
Example:
<?php
$str = "GeeksforGeeks!" ;
$n = 6;
$start = strlen ( $str ) - $n ;
$str1 = substr ( $str , $start );
echo $str1 ;
?>
|
Note: In above example, $start can also take -N to create a sub-string of last n characters
Share your thoughts in the comments
Please Login to comment...