Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the last 7 characters of a PHP string?

Tags:

string

php

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 
like image 973
Dave Avatar asked May 10 '12 21:05

Dave


People also ask

How can I get the last character of a string in PHP?

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.

How do I get last 4 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.

How do you get the last few characters of a 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.

How can I remove last 4 characters from a string in PHP?

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 .


1 Answers

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.

like image 167
Asaph Avatar answered Sep 21 '22 13:09

Asaph