RegEx & PHP 多个变量
RegEx & PHP multiple variabels
我第一次忙于正则表达式PHP。
我想做一个车牌检查器,在字母和数字之间加上'-'。现在一切正常,但唯一的问题是对于每个字符串我都会得到另一个变量。
喜欢:对于 999TB2,我得到 $1 $2 $3,但第二个字符串 9999XX 将是 $4 $5 $6。是否有可能获得第二个字符串 $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 = '-- --';
$result = preg_replace($re, $subst, $str, 1);
echo "The result of the substitution is ".$result;
?>
亲切的问候
您可以使用分支重置组 (?|
并且您可以从模式中省略 {1}
。
^(?|(\d{3})([A-Z]{2})(\d)|(\d{2})(\d{2})([A-Z]{2}))$
看到一个regex demo and a PHP demo。
示例代码
$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, '--', $str) . PHP_EOL;
}
输出
999-TB-2
99-99-XX
我第一次忙于正则表达式PHP。
我想做一个车牌检查器,在字母和数字之间加上'-'。现在一切正常,但唯一的问题是对于每个字符串我都会得到另一个变量。
喜欢:对于 999TB2,我得到 $1 $2 $3,但第二个字符串 9999XX 将是 $4 $5 $6。是否有可能获得第二个字符串 $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 = '-- --';
$result = preg_replace($re, $subst, $str, 1);
echo "The result of the substitution is ".$result;
?>
亲切的问候
您可以使用分支重置组 (?|
并且您可以从模式中省略 {1}
。
^(?|(\d{3})([A-Z]{2})(\d)|(\d{2})(\d{2})([A-Z]{2}))$
看到一个regex demo and a PHP demo。
示例代码
$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, '--', $str) . PHP_EOL;
}
输出
999-TB-2
99-99-XX