Home > Net >  RegEx & PHP multiple variabels
RegEx & PHP multiple variabels

Time:05-29

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?

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

CodePudding user response:

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
  • Related