Php preg_match 模式
Php preg_match pattern
我有一个表单域,我想检查用户是否提交了正确的模式。我这样试过。
// $car_plate should in XXX-1111, or XXX-111(three letters in uppercase followed by a dash and four or three numbers)
<?php
$car_plate = $values['car_plate'];
if (!preg_match('[A-Z]{3}-[0-9]{3|4}$', $car_plate)) {
$this->errors ="Pattern for plate number is XXX-1111 or XXX-111";
} else {
// code to submit
}
?>
以下 car_plate 号码格式正确(AAA-456、AGC-4567、WER-123)。在这种情况下,它总是 return 错误。正确的做法是什么?
看起来你的正则表达式有点不对。
试试这个:
/^[A-Z]{3}-[0-9]{3,4}$/
在 PHP 中,您必须用 delimiters, in this case the slashes. In addition to that, {3|4}
is not valid, the correct syntax is {3,4}
as you can see in the docs covering repetition.
将正则表达式括起来
替代 TimoSta 的答案。
/^[a-zA-Z]{3}-?\d{3,4}$/
这允许用户输入小写字母并跳过破折号
您稍后可以像这样格式化数据:
$input = 'abc1234';
if ( preg_match( '/^([a-zA-Z]{3})-?(\d{3,4})$/', $input, $matches ) )
{
$new_input = strtoupper( $matches[1] ) . '-' . $matches[2];
echo $new_input;
}
输出:ABC-1234
我有一个表单域,我想检查用户是否提交了正确的模式。我这样试过。
// $car_plate should in XXX-1111, or XXX-111(three letters in uppercase followed by a dash and four or three numbers)
<?php
$car_plate = $values['car_plate'];
if (!preg_match('[A-Z]{3}-[0-9]{3|4}$', $car_plate)) {
$this->errors ="Pattern for plate number is XXX-1111 or XXX-111";
} else {
// code to submit
}
?>
以下 car_plate 号码格式正确(AAA-456、AGC-4567、WER-123)。在这种情况下,它总是 return 错误。正确的做法是什么?
看起来你的正则表达式有点不对。
试试这个:
/^[A-Z]{3}-[0-9]{3,4}$/
在 PHP 中,您必须用 delimiters, in this case the slashes. In addition to that, {3|4}
is not valid, the correct syntax is {3,4}
as you can see in the docs covering repetition.
替代 TimoSta 的答案。
/^[a-zA-Z]{3}-?\d{3,4}$/
这允许用户输入小写字母并跳过破折号
您稍后可以像这样格式化数据:
$input = 'abc1234';
if ( preg_match( '/^([a-zA-Z]{3})-?(\d{3,4})$/', $input, $matches ) )
{
$new_input = strtoupper( $matches[1] ) . '-' . $matches[2];
echo $new_input;
}
输出:ABC-1234