简体   繁体   中英

How can I get the last position of letters in a string formed by letters and numbers in php

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?

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;
}

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

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

list($characters,$digits) = sscanf('%[A-Z]%d', $myString);
$lastCharacter = substr($characters, -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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM