dongren1977 2016-06-20 16: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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效