Current Location: Home> Latest Articles> How to Read the Last Few Characters of a String in PHP? Simple and Easy Implementation

How to Read the Last Few Characters of a String in PHP? Simple and Easy Implementation

gitbox 2025-06-25

How to Read the Last Few Characters of a String in PHP

In PHP, if you need to read the last few characters of a string, you can use the substr() function. This function allows you to extract a portion of the string and return it. Below, we will detail the usage of the substr() function to help you better understand how to achieve this task.

1. Read the Last N Characters of a String

To read the last N characters of a string, you first need to calculate the length of the string. Then, use the substr() function to extract the last N characters. Here's a simple example of how to do it:

$string = 'Hello, World!';
$num = 3;  // The number of last characters to read
$length = strlen($string);  // Get the string length
$result = substr($string, $length - $num, $num);  // Extract the last N characters of the string
echo $result;

In this code, we first assign the string we want to process to the variable ```$string```, and specify the number of characters to read with the variable ```$num```. We then use the ```strlen()``` function to get the length of the string and calculate the starting position from the end of the string. Finally, we use the ```substr()``` function to extract the last N characters and store the result in the variable ```$result```. By using ```echo```, the output will be ```ld!```.

2. Encapsulating the Method to Read the Last Few Characters of a String

To make it more reusable, we can encapsulate the logic of reading the last few characters into a function. Here's how you can do it:

function getLastChars($string, $num) {
    $length = strlen($string);
    return substr($string, $length - $num, $num);
}

$string = 'Hello, World!';
$num = 3;
$result = getLastChars($string, $num);
echo $result;

In this example, we define a function called ```getLastChars()```, which accepts two parameters: the string to be processed and the number of last characters to read. The implementation inside the function is similar to the previous example, but we've encapsulated the logic in a reusable function. By calling ```getLastChars()```, we can easily extract the last N characters of any string, and the output will again be ```ld!```.

Conclusion

In PHP, reading the last few characters of a string can be easily achieved using the substr() function. By calculating the string's length and utilizing the characteristics of substr(), you can efficiently extract the required portion of the string. If you need to perform this operation frequently, encapsulating the logic into a function is a good approach, as it increases code reusability.