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

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)

You don't need the capture group (parenthesis) unless you want to know what the trailing numbers are. But looks like you just want to check if it contains lease/{number}

You can try this:

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

contains lease, then a slash, then 1+ number