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

RegEx & PHP multiple variabels

For the first time i am busy with Regex with PHP.

I want to make a licenseplate checker and put ‘-‘ between the letters and numbers. Everything works for now but the only one problem is that for every string i get another variable.

Like: for 999TB2 i get $1 $2 $3 but the second string 9999XX will be $4 $5 $6. Is it possible to get for the second string also $1 $2 $3?

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

<?php
$re = '/^(\d{3})([A-Z]{2})(\d{1})|(\d{2})(\d{2})([A-Z]{2})$/';
$str = '9999XX'; //(Will be later connected to database)
$subst = '$1-$2-$3 $4-$5-$6';

$result = preg_replace($re, $subst, $str, 1);
echo "The result of the substitution is ".$result;

?>

Kind regards

>Solution :

You can use a branch reset group (?| and you can omit {1} from the pattern.

^(?|(\d{3})([A-Z]{2})(\d)|(\d{2})(\d{2})([A-Z]{2}))$

See a regex demo and a PHP demo.

Example code

$strings = [
    "999TB2",
    "9999XX"
];

$re = '/^(?|(\d{3})([A-Z]{2})(\d)|(\d{2})(\d{2})([A-Z]{2}))$/';

foreach ($strings as $str) {
    echo preg_replace($re, '$1-$2-$3', $str) . PHP_EOL;
}

Output

999-TB-2
99-99-XX
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