I need to get the last character of a string. Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
To get the first character from a string, we can use the substr() function by passing 0,1 as second and third arguments in PHP.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
substr("testers", -1); // returns "s"
Or, for multibytes strings :
substr("multibyte string…", -1); // returns "…"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With