How do I get the last n characters of a PHP string?

PHP

Examples:
Input: $str = "GeeksforGeeks!" $n = 6 Output: Geeks! Input: $str = "GeeksforGeeks!" $n = 9 Output: forGeeks! 
Method 1: Usethis method, look at the last N characters of the line and keep adding them to a new line.Example: < td class = "code"> $str = "GeeksforGeeks!" ; $n = 6;  
// Line starting index
// where a new line starts $start = strlen ( $str ) - $n ;  
// New line $str1 = `` ; for ( $x = $start ; $x < strlen ( $str ); $x ++) { // Add characters to a new line $str1 . = $str [ $x ]; }  
// Print a new line echo $str1 ; ?>
Exit:
Geeks! 
Method 2:Another way to do this - use the built-in library function substr with parameters as the string name.Example : $str = " GeeksforGeeks! " ; $n = 6; $start = strlen ( $str ) - $n ;  
// substr returns a new line. $str1 = substr ( $str , $start ); echo $str1 ; ?>
Exit:
Geeks! 
Note.In the above example, $start can also take -N to create a substring of the last n characters.



Get Solution for free from DataCamp guru