[SOLVED] Substr() offset negative

From what I have been able to test, the subtr () function does not work with negative offset, I mean the start and length values from the end of the string. Examples:

<?php
$rest = substr(“abcdef”, -1); // returns “f”
$rest = substr(“abcdef”, -2); // returns “ef”
$rest = substr(“abcdef”, -3, 1); // returns “d”
?>

1 Like

That is accurate. Just as in most versions of Javascript, the substring expression (SubStr()) starts from 0. It does not loop.

You can test this similarly in Javascript here:

A specific excerpt that is relevant to you:

If either or both of the arguments are negative or NaN , the substring() method treats them as if they were 0 .

console.log(text.substring(-5, 2))  // => "Mo"
console.log(text.substring(-5, -2)) // => ""
1 Like

In JavaScript there is also the substr expression that does support negative numbers, but it has been deprecated String.prototype.substr() - JavaScript | MDN

1 Like

I am using a workaround as it is deprecated:

substr( string, stringlenght(string) -number, number)