Retrieve a substring from the end in PHP

To extract a substring from the end of a string using the PHP's mb_substr function, specify the length of the target string minus the length of the substring as the extraction start position.

The PHP mb_substr function performs the same way when you specify a negative value (like -1) as the extraction start position, but the method mentioned above is useful to remember as it applies to any programming language.

Source Code


/**
 * Retrieves a substring from the end of the given string
 * @param string $str The string
 * @param int $len The length of the substring (number of digits)
 * @return string The substring
 */
function substringFromEnd(string $str, int $len) {
    return mb_substr($str, mb_strlen($str) - $len, $len);
}

Validation

Input Arguments
Fixed Display

substringFromEnd("
",
);

Enter the length in number of digits.

Validation Result

Half-width and full-width spaces will be converted to underscores.

Follow me!

photo by:Thought Catalog