Home > Software design >  PHP Regex match one letter and one number
PHP Regex match one letter and one number

Time:02-04

I'm trying to replace any occurrences when you find a single letter followed by a single number in a string.

$word = 'AB001J1'; //or ZR010F2 or ZQ10B5

echo str_replace('/^(?=.*\pL)(?=.*\p{Nd})/', '', $word);

Trying to get the result AB001 //or ZR010 or ZQ10

CodePudding user response:

A regex splitting approach works well here:

$word = 'AB001J1';
$output = preg_split("/(?<=[0-9])(?=[A-Z])/", $word, 2)[0];
echo $output;  // AB001

The above strategy is to split the input string at any point in between a digit and uppercase letter (in that order). This separates the various terms, and we retain only the first one.

  •  Tags:  
  • Related