Search code examples
phpregexroutespreg-matchpreg-match-all

How to find an exact match using regex in PHP?


I have some problems when trying to make a match with my URL with my regex pattern in PHP.

my regex:

/article/([0-9A-Za-z]++)/post/([0-9A-Za-z-_]++)

public function matches(Route $route){
    $uri = filter_var(strip_tags($_SERVER['REQUEST_URI']), FILTER_SANITIZE_URL);
    if (preg_match('#' . "/article/([0-9A-Za-z]++)/post/([0-9A-Za-z-_]++)" . '#i', $uri, $this->matches)) {
        return true;
    }
    return false;
}

example 1: VALID MATCH (good)

/article/AB545455DSAF54FSA45S4F4/post/FGFG-FGFGF-5FG54FGF-FGFGFG

but also matches this (bad):

/article/AB545455DSAF54FSA45S4F4/post/FGFG-FGFGF-5FG54FGF-FGFGFG/fgfg/fgfgfg/fgf

I want only to match the first example, so how do i fix this? thanks


Solution

  • Add a terminating anchor to your regex:

    /article/([0-9A-Za-z]+)/post/([0-9A-Za-z-_]+)$
                                                 ^^^
    

    The anchor will ensure that no more subdirectories can appear after the final component.

    public function matches(Route $route){
        $uri = filter_var(strip_tags($_SERVER['REQUEST_URI']), FILTER_SANITIZE_URL);
        if (preg_match('~/article/[0-9A-Za-z]+/post/[0-9A-Za-z_-]+$~", $this->matches)) {
            return true;
        }
        return false;
    }
    

    Note that matching something in regex one or more times uses a single plus, not two of them.

    I may not have your exact code working here, but the pattern I suggest appears to work in the demo below.

    Demo