反直觉的preg_match行为 - 匹配一系列字符的最简洁方法是什么?

问题描述:

I am looking for ways to match a range of characters and assumed the following regEx would only match characters in the range of hex codes between 20 and 7E. However, it also matches chr(10) (line feed), in fact, the following prints "passed":

echo preg_match("/^[\x20-\x7E]*$/", chr(10)) ? 'passed' : 'failed';

Any idea why and how to match that range?

我正在寻找匹配一系列字符的方法,并假设以下regEx只匹配范围内的字符 十六进制代码在20到7E之间。 但是,它也匹配 chr(10) code>(换行),实际上,以下打印“传递”: p>

  echo preg_match(“/  ^ [\ x20- \ x7E] * $ /“,chr(10))?  '通过':'失败'; 
  code>  pre> 
 
 

知道为什么以及如何匹配该范围? p> div>

chr(10) is end of line, so you should add 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';
//                               ^