phpregexquantifiers

Make trailing characters non-optional in a regex pattern


I have a little problem with a reqular expression in my application. I have following code which works well for all patterns, that are not just '/':

if (preg_match("#". $pattern1 . "(/.*+)?#", $pattern2)) {
    $topActive = TRUE;
}

When I have $pattern1 with /line-up or /line-up/opening and $pattern2 with /line-up/opening it works as expected. But it also matches when I have just '/' as $pattern1. what can I do to prevent matching against '/', but let it still match against the other mentioned patterns?


Solution

  • I have found a solution for my problem. I have to check the found matches against the pattern again.

    if (preg_match("#". $menuRoute->getPattern() . "(/.+)?#", $route->getPattern(), $matches)) {
        if (isset($matches[0]) && $matches[0] == $route->getPattern()) {
        $topActive = TRUE;
        }
    }