skip to Main Content

I have a few hundred thousand strings that are laid out like the following

AX23784268B2
LJ93842938A1
MN39423287S
IY289383N2

With PHP I’m racking my brain how to return B2, A1, S, and N2.

Tried all sorts of substr, strstr, strlen manipulation and am coming up short.

substr('MN39423287S', -2); ?> // returns 7S, not S

2

Answers


  1. There’s many way to do this.
    One example would be a regex

    
    <?php
    
    $regex = "/.+([A-Z].?+)$/";
    
    $tokens = [
    'AX23784268B2',
    'LJ93842938A1',
    'MN39423287S',
    'IY289383N2',
    ];
    
    foreach($tokens as $token)
    {
        preg_match($regex, $token, $matches);
        var_dump($matches[1]);  
        // B2, A2, S, N2
    }
    
    

    How the regex works;

    .+       - any character except newline
    (        - create a group
      [A-Z]  - match any A-Z character
      .?+    - also match any characters after it, if any
    )        - end group
    $        - match the end of the string
    
    Login or Signup to reply.
  2. This is a simpler regexp than the other answer:

    preg_match('/[A-Z][^A-Z]*$/', $token, $matches);
    echo $matches[0];
    

    [A-Z] matches a letter, [^A-Z] matches a non-letter. * makes the preceiding pattern match any number of times (including 0), and $ matches the end of the string.

    So this matches a letter followed by any number of non-letters at the end of the string.

    $matches[0] contains the portion of the string that the entire regexp matched.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search