Home > Enterprise >  I need a regexp to parse in php a car license plate
I need a regexp to parse in php a car license plate

Time:07-15

I have a string that can contain multiple car license plates. In Spain licence car plates are composed by four digits and three letters, but the user can separate them by an space or a hyphen. So I have this regular expresion to try to match all cases.

(\d{4})( *)(-*)( *)([a-zA-Z]{3})

So it acceps 1234 ABC or 1234ABC or 1234-ABC.

My problem is when a user inserts multiples car plates in same input text field. I can get values like 1234 ABC 4567BCX and I need to separate them in an array with one car license plate for each array position. Here is the php code I'm trying but it does not work...

$matricula = "1234 ABC 2345 rBC";
$regexp1 = '/(\d{4})( *)(-*)( *)([a-zA-Z]{3})/';
$regexp2 = '/((\d{4})( *)(-*)( *)([a-zA-Z]{3})( )*) /';
preg_match($regexp2,$matricula,$matches);
$result = array_shift($matches);
var_dump($matches);

var_dump(preg_split($regexp2, $matricula));

Can any body help me please?

CodePudding user response:

This might be an approach:

<?php
$input = "1234-ABC 2345 rBC 9998DDD 9657   lJi";
preg_match_all('/(\d{4}[-\s]*[a-z]{3})/i', $input, $matches);
$output = array_shift($matches);
array_walk($output, function(&$value) {
    $value = strtoupper(str_replace(" ", "", $value));
});
print_r($output);

The output obviously is:

Array
(
    [0] => 1234ABC
    [1] => 2345RBC
    [2] => 9998DDD
    [3] => 9657LJI
)

CodePudding user response:

You regular expression (\d{4})( *)(-*)( *)([a-zA-Z]{3}) was correct but you needed to use preg_match_all to return multiple matches.

This is a demo:

https://onlinephp.io/c/e5acb

<?php

function parsePlates($subject){
    $plates = [];
    preg_match_all('/(\d{4})( *)(-*)( *)([a-zA-Z]{3})/sim', $subject, $result, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($result[0]); $i  ) {
        $plate = $result[0][$i];
        $plates[] = $plate;
    }
    return $plates;
}

$plates = parsePlates('1234 ABC 4567BCX');
var_dump($plates);
  • Related