-2

I have a string like any of the following:

$str = 'A001';
$str = 'B001';
$str = 'AB001';
$str = 'B0015';
....
$str = '001A';

I want to keep only 3 characters from the end of each string.

My code is like this:

 $code = str_split($str);
 $code = $code[1].$code[2].$code[3];

But it works for specific cases, but not for general ones! How I can get it for general ones?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
koe
  • 736
  • 1
  • 12
  • 33

3 Answers3

2

I want to keep every 3 character from end of string

Simply Use substr

echo substr($str,-3);    // Last 3 characters

Second parameter to this function is start, and according to the Manual

If start is negative, the returned string will start at the start'th character from the end of string.

Fiddle

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
0

Use sbstr()

echo substr($str,-3);//get last 3 char char

Or try:

echo $str[strlen($str)-3].$str[strlen($str)-2].$str[strlen($str)-1];
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

You need to use substr function.

All you need to do is to pass the string, and tell it where you cut the string off. If you want to cut the string off from end, you have to provide the value in negative.

substr($str, -3);
// The third argument is optional, which specifies the length of the returned string.
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76