regular expression false delimiter in wordpress

2019-02-27 01:34发布

I am newbie to regular expression and I have this simple doubt.

I have found this code in wordpress

$self = preg_replace('|^.*/wp-admin/|i', '', $self); 

according to the doc on php.net | is not permissible as delimiter..

Can someone explain the code?

1条回答
放我归山
2楼-- · 2019-02-27 01:46

Have you tried it?

From your link:

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

So | is a perfectly valid delimiter. When you read the comments on that page, they suggest to not use meta characters (like |) as delimiters, when they should be used inside the regex.

Since there is no alternation in your example $self = preg_replace('|^.*/wp-admin/|i', '', $self); there is no problem and it is working as expected.

When you have an alternation in the regex (e.g. preg_match("|(F|f)oo|", "Foobar")) you will get a warning "Unknown modifier 'f'", because the interpreter thinks the regex does end at the first alternation.

Conclusion: It's allowed, but not recommended to use regex meta-characters like |, ^, +, ... as regex delimiters.

查看更多
登录 后发表回答