Search code examples
phptrimregex-negationtruncate

PHP RegEx Excluding TWO strings from string


After searching various other questions in order attempt solving this on my own, I've gotten this far yet I cannot figure out how add an additional string.

// $url will actually be $_SERVER['REQUEST_URI']
$url = "/folder123/?id=foo"; // it could be "index.php?id=foo"

preg_replace_callback('#^/folder123/#', function($match) {
    return $match[1];
}, $url);

Expected Result: ?id=foo

With my current code, I'll get the expected result; however I don't know how to also check for index.php. My intention is to have the string exclude these two parts.


Solution

  • To match them both you might use an alternation followed by \K to reset the starting point of the reported match.

    ^(?:/folder123/|index\.php)\K.*$

    preg_replace_callback('#^(?:/folder123/|index\.php)\K.*$#', function($match) { return $match[0]; }, $url);
    

    Demo