PRIG_MATCH错误未知修饰符'('

2022-03-29 00:00:00 regex php preg-match

这有什么问题?

public static function validaDataHoraBR($data_hora){
  $pattern = "/^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$/";
  return (preg_match($pattern, $data_hora)) ? array(true) : array(false,' não é uma data e hora no formato BR!<br>'); 
}

此模式验证-20/08/2011 21:00:00

错误:消息:preg_Match()[function.preg-Match]:未知修饰符‘(’


解决方案

在正则表达式中转义/

"/^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$/"
#                                   ^                 ^

否则,/将被识别为正则表达式的末尾。

或使用不同的分隔符:

"#^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$#"

相关文章