user3312508 user3312508 - 1 year ago 72
PHP Question

PHP - preg_match regex

I am trying to use

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.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download