preg_match错误未知修饰符'('

时间:2013-11-01 12:19:44

标签: php regex 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 个答案:

答案 0 :(得分:3)

在正则表达式中转义/

"/^([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}$#"