PHP独特的正则表达式

code:

1
2
// php 7.2.16
var_dump(preg_match("/^[a-z]+$/", "abc\n")); // true
1
2
// javascript
console.log("/^[a-z]+$/".test("abc\n")); // false
1
2
// java(jdk11)
System.out.println(Pattern.matches("^[a-z]+$", "abc\n")); // false

Php使用的是 Perl特性的匹配规则,所以要想达到下面的效果需要在使用

/^[a-z]+$/n/(*CRLF)^[a-z]+$/

php文档中关于此段的解释 https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

“Because Perl returns a string with a newline at the end when reading a line from a file, Perl’s regex engine matches $ at the position before the line break at the end of the string even when multi-line mode is turned off. Perl also matches $ at the very end of the string, regardless of whether that character is a line break. So ^\d+$ matches 123 whether the subject string is 123 or 123\n.”

“D (PCRE_DOLLAR_ENDONLY)

If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.”

关注作者公众号,获取更多资源!
赏作者一杯咖啡~