0

I am trying to make an automatic counter to get the last id of my database. I keep rows with an alphanumeric id:

AR1, AR2, AR3, TER17, KAKAP126...

it is varchar in database so I cannot make a +1. So I want to detect the end of the chars (letters) and delete them from the id, add +1 and concat the number to the letters part.

I tried this:

$s = $rowAtt['id']; (ie: TUR99)
echo $s;
echo "<br>";

for ($i = 1; $i <= strlen($s); $i++){
   $char = $a[$i-1];
   if (is_numeric($char)) {
      echo $char . ' is a number<br>';
   } else {
      echo $char . ' is a letter<br>';
   }
}

But It says always "is a letter"...

What can I do for that?

Biribu
  • 3,615
  • 13
  • 43
  • 79

6 Answers6

2

Here is something you could try.

function getLastLetter($str) {
    $str = preg_replace('/[^a-zA-Z]/', '', $str);
    return substr($str, -1);
}

function getLastLetterPosition($str) {
    $str = preg_replace('/[^a-zA-Z]/', '', $str);
    return strlen($str) - 1;
}
mts7
  • 583
  • 4
  • 12
2

To get both the character and the numeric part separately:

  $testString="AAAK12";

  $chars = preg_split("/[0-9]+/", $testString);
  $nums = preg_split("/[a-zA-Z]+/", $testString);

  echo "Chars are " . $chars[0] . "\n";
  echo "Nums are " . $nums[1] . "\n";

Result:

Chars are AAAK
Nums are 12
ebo
  • 2,717
  • 1
  • 27
  • 22
1

Simple function that will return the last character, what you do with it is up to you:

function getLastChar($string)
{
  $newString = strrev($string);
  for($i=0;$i<=strlen($string);$i++)
  {
    if(!is_numeric($newString[$i])) return $newString[$i];
  }
  return false;
}

echo getLastChar('askdjwu12312');

result: u

skrilled
  • 5,350
  • 2
  • 26
  • 48
1
list($characters,$digits) = sscanf('%[A-Z]%d', $myString);
$lastCharacter = substr($characters, -1);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

Use string length as index:

A string in PHP can also behave as an array of chars. Therefore we can access each one of them via a simple syntax like: $string[n]. Everything else is a matter of using the string length as the index to retrieve the last letter.

This can be translated in code as follows:

$myString = 'Hello World';
$lastLetter = $myString[strlen($myString)-1];

Regards, M

Manuel Ro
  • 206
  • 3
  • 10
0

The php manual on substr says just use substr($foo, -1). Did you try that?

MueR
  • 977
  • 7
  • 13