我正在寻找匹配一系列字符的方法,并假设以下正则表达式仅匹配 20 到 7E 之间的十六进制代码范围内的字符。然而,它也匹配chr(10)
(换行),事实上,以下打印“passed”:
echo preg_match("/^[\x20-\x7E]*$/", chr(10)) ? 'passed' : 'failed';
知道为什么以及如何匹配该范围吗?
最佳答案
chr(10) 是行尾,因此您应该添加 modifier D.
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).
// v
echo preg_match("/^[\x20-\x7E]*$/D", chr(10)) ? 'passed' : 'failed';
// ^
关于php - 违反直觉的 preg_match 行为 - 匹配一系列字符的最简洁的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586526/