• Reset your password
Home
OO PHP, Drupal, Symfony Developer and Architect
Tim Rabbetts

Main navigation

  • Home
  • Blog
  • Log in

PHP: How to Retrieve String at the End with substr and strrpos

Breadcrumb

  • Home
  • blog
  • php how to retrieve string at the end with substr and strrpos
  • PHP: How to Retrieve String at the End with substr and strrpos
Tim
Rabbetts
By zarexogre | 8:57 AM UTC, Wed July 09, 2025

In PHP, there are various functions and methods available to manipulate strings. One common task is to retrieve a substring located at the end of a larger string. Two functions that are often used for this purpose are substr and strrpos.

Using substr Function

The substr function in PHP is used to extract a part of a string. It takes two parameters: the input string and the starting position from where the extraction should begin. If the starting position is provided as a negative value, it counts from the end of the string.

Here is an example of how you can use the substr function to retrieve a string at the end:

$originalString = 'This is a test string'; $substring = substr($originalString, -5); echo $substring;

This code will output 'string', which is the last 5 characters of the original string.

Using strrpos Function

The strrpos function in PHP is used to find the position of the last occurrence of a substring in a string. It takes two parameters: the input string and the substring to search for.

Here is an example of how you can combine strrpos with substr to retrieve a string at the end:

$originalString = 'This is a test string'; $lastSpacePosition = strrpos($originalString, ' '); $substring = substr($originalString, $lastSpacePosition + 1); echo $substring;

This code will output 'string' by finding the position of the last space character and extracting the substring located after it.

By using these functions in combination, you can easily retrieve a string at the end of a larger string in PHP.