Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

php - How the preg_match handles the delimiter when Q..E used?

I'm playing with regular expressions and I tried the Q..E escape sequence.

First try:

$regex = '/Q http:// E/';
var_dump(preg_match($regex, ' http:// '));

It tells me that '' is unknown modifier, completely understandable.

Second try:

$regex = '/Q http:// E/';
var_dump(preg_match($regex, ' http:// '));
var_dump(preg_match($regex, ' http:// '));

It runs, not match the first string, but match the second one.

I know that I could use other delimiter character or solve it without Q..E, but I'm curious that how it works.

I through that at first it separates the regex from the modifiers by the delimiter (with handling the escaping if necessary) and after that the regex engine interprets the Q..E, but it seems like that when the Q involved, then it not handles the escaped delimiter the same way.

What happens exactly at this case?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Q and E can be used to ignore regular expression metacharacters in the pattern.

If the literal string contains the delimiter / for example, the regular expression compile fails or the match fails because it tries to match the escape character used to escape the delimiter. Delimiters that are between Q E should be treated as literal characters, not delimiters.

preg_match('~Q http:// E~', ' http:// ', $match);
var_dump($match);

# => array(1) { [0]=> string(7) " http:// " }

Use preg_quote() instead of Q E if the delimiter may appear within Q E

$text = ' http:// ';

preg_match('/' . preg_quote($text, '/') . '/', $text, $match);
var_dump($match);

# => array(1) { [0]=> string(9) " http:// " }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...