1

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

1
  • Here a different idea. It's more generic, not sure if that fits your needs. Commented May 29, 2022 at 11:26

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.