PHP Get Last 2 Characters from String Example

03-Apr-2023

.

Admin

PHP Get Last 2 Characters from String Example

Hi Dev,

In this example, you will learn php get last 2 Characters from string example. Here you will learn how to get last two Characters from string in php?. I would like to share with you get last two Characters from string in php example. In this article, we will implement a how to use function to get last two Character from string in php?.

There are tow example to get Last 2 Characters from strings in PHP. in this example, we will use to substr() and mb_substr() function to get Last 2 Characters. so Let's both the following example with output.

Example 1: Get Last 2 Characters from String


index.php

<?php

$str = "Nicesnippets";

//Get Last Two Characters from a String

$result = substr($str, strlen($str)-2);

echo $result;

?>

Output:

ts

Example 2: Get Last 2 Characters from String

index.php

<?php

$str = "Hello World";

//Get Last Two Characters from a String

$result = mb_substr($str, -2);

echo $result;

?>

Output:

ld

I hope it could help you...

#PHP