Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need a regexp to parse in php a car license plate

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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?

>Solution :

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading