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 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。
  • ¥15 已知隐函数其中一个变量τ的具体值,求另一个变量
  • ¥15 r语言Hurst指数
  • ¥15 Acrn IVSHMEM doorbell问题
  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题
  • ¥15 materialstudio氢键计算问题
  • ¥15 echarts图表制作