RG Servers
RG Servers

Reputation: 1784

PHP Regex match one letter and one number

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

Upvotes: 0

Views: 63

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520958

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.

Upvotes: 2

Related Questions