How would I go about grabbing the last 7 characters of the string below?
For example:
$dynamicstring = "2490slkj409slk5409els"; $newstring = some_function($dynamicstring); echo "The new string is: " . $newstring;
Which would display:
The new string is: 5409els
The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
To get substring having last 4 chars first check the length of string. If string length is greater than 4 then substring(int beginIndex) method. This method takes index position as method argument and return the complete string from that specified index.
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.
You can use the PHP substr_replace() function to remove the last character from a string in PHP. $string = "Hello TecAdmin!"; echo "Original string: " . $string .
Use substr()
with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )
If start is negative, the returned string will start at the start'th character from the end of string.
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