dongmingxiang0312 2016-09-24 01:48
浏览 131
已采纳

在PHP中匹配特定的字符串格式

I know there are many similar questions on SO about regex and matching, but I just cant get this to work!

I need to check if my string is in the specific format of:

13:30 - 14:00

2 numbers, colon, 2 numbers, space, dash, space, 2 numbers, colon, 2 numbers

This is my best effort so far...

$string = "13:30 - 14:00";
$regex = '^[0-9]{2}:[0-9]{2} - [0-9]{2}:[0-9]{2}$';
if (preg_match($regex, $string)) {
echo "matched pattern";
}

I am a regex noob, and I'm not sure why this isnt working.

Can someone help me to get this regex matching working?

  • 写回答

4条回答 默认 最新

  • dounieliang4712 2016-09-24 01:51
    关注

    First: regexp should start/end with / (or #)

    Second: - is a special symbol and should be escaped with \

    $string = "13:30 - 14:00";
    $regex = '/^[0-9]{2}:[0-9]{2} \- [0-9]{2}:[0-9]{2}$/';
    if (preg_match($regex, $string)) {
        echo "matched pattern";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部