dongren1977 2016-06-20 08:07
浏览 51
已采纳

PHP - preg_match正则表达式

I am trying to use preg_match to figure out if a url has certain pattern and right now its not working as I expected. Heres what I have so far:

if(! preg_match('^lease/([0-9]+)/?', $url)) {
    wp_redirect( home_url(), 301 );
}

Basically I want to see if the url pattern is as below(lease keyword followed by a number) and if not the page should be redirected to homepage. Im not good with regex so I need some help with this one. TIA. www.example.com/lease/324

  • 写回答

2条回答 默认 最新

  • douhuan6305 2016-06-20 08:17
    关注

    You need to allow any chars before the /lease with .*?, an end of string anchor $ and regex delimiters (I prefer ~ so as not to escape forward slashes):

    if(! preg_match('~^.*/lease/([0-9]+)/?$~', $url)
    

    Or you may omit ^.*? part since preg_match allows partial matches

    if(! preg_match('~/lease/([0-9]+)/?$~', $url)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部