[英]RegEx & PHP multiple variabels
For the first time i am busy with Regex with PHP.我第一次忙于使用 PHP 的 Regex。
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.比如:对于 999TB2,我得到 1 美元 2 美元 3 美元,但第二个字符串 9999XX 将是 4 美元 5 美元 6 美元。 Is it possible to get for the second string also $1 $2 $3?
是否有可能获得第二个字符串也 $1 $2 $3?
<?php $re = '/^(\d{3})([AZ]{2})(\d{1})|(\d{2})(\d{2})([AZ]{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亲切的问候
You can use a branch reset group (?|
and you can omit {1}
from the pattern.您可以使用分支重置组
(?|
并且可以从模式中省略{1}
。
^(?|(\d{3})([A-Z]{2})(\d)|(\d{2})(\d{2})([A-Z]{2}))$
See a regex demo and a PHP demo .请参阅正则表达式演示和PHP 演示。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.