How to Get Last 2, 3, 4, 5, 7 Characters of a String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hello Dev,

Here, I will show you how to get last two characters of a string in php. We will use php get last 4 characters of string. you will learn php get last 3 characters of string. If you have a question about php get last 5 characters of string then I will give a simple example with a solution.

In this example, we will use substr() function to get last 2, 3, 4, 5 and 7 characters from string in php. so, let's see the following example code:

index.php

<?php

$string = "Welcome to ItSolutionstuff.com";

$last2Char = substr($string, -2);

var_dump($last2Char);

$last3Char = substr($string, -3);

var_dump($last3Char);

$last4Char = substr($string, -4);

var_dump($last4Char);

$last5Char = substr($string, -5);

var_dump($last5Char);

$last7Char = substr($string, -7);

var_dump($last7Char);

?>

Output:

string(2) "om"

string(3) "com"

string(4) ".com"

string(5) "f.com"

string(7) "uff.com"

I hope it can help you...

Tags :
Shares