Literal delimiter ( delimiter inside \\Q \\E block

2020-04-18 05:32发布

问题:

I've been trying to make a few of functions based on RegEx and most of them use \Q and \E as some of the RegEx pattern is user input.

So, let's say hypothetically that we're using the delimiter / and want to match it against / the function would construct something amongst the lines of /\Q/\E/.

I'm not sure why /\Q/\E/ doesn't match / but with every other delimiter it does, unless you use the same delimiter as input.

Maybe, it considers the delimiter the end, even though, it's in a literal-only block and the escape as literal. Not sure, tried a bunch.

Hopefully someone can push me into the right direction as to what workarounds there are for this issue.

回答1:

It helps to understand that / is not a regex metacharacter, like * or (. It's special because you're using it to delimit the regex itself, and the only way to escape the regex delimiter is with a backslash (\/).

But you shouldn't need to use \Q and \E. The preg_quote() method takes a delimiter argument, so it correctly adds backslashes everywhere they're needed.



标签: php regex pcre