php - 正则表达式除空格外的任何字符

标签 php regex whitespace

我正在创建一个密码验证器,它接受除空格以外的任何字符,并且至少有 6 个字符。

在搜索了最好的之后,我找到了这个例子: What is the regular expression for matching that contains no white space in between text?

它不允许中间有任何空格,但允许以空格开头和结尾。我想禁止传递的字符串中有任何空格。

我试过了,但没用:

if (preg_match("/^[^\s]+[\S+][^\s]{6}$/", $string)) {
  return true;
} else {
  return false;
}

谢谢。

最佳答案

像这样:

/^\S{6,}\z/

可以这样引用:

preg_match('/^\S{6,}\z/', $string)

所有使用 $ 的答案都是错误的(至少没有任何特殊标记)。如果您不想在字符串末尾使用换行符,则应使用 \z 而不是 $

  • $ 匹配字符串结尾或之前字符串结尾的换行符(如果没有修饰符用过)
  • \z 匹配字符串结尾(独立于多行模式)

来自 http://www.pcre.org/pcre.txt :

 ^           start of subject
              also after internal newline in multiline mode
 \A          start of subject
 $           end of subject
              also before newline at end of subject
              also before internal newline in multiline mode
 \Z          end of subject
              also before newline at end of subject
 \z          end of subject

关于php - 正则表达式除空格外的任何字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6808310/

相关文章:

css - 在 Chrome 中检查元素时空白消失

javascript文本匹配计数和正则表达式空格不起作用

javascript - 出现错误 Uncaught ReferenceError : jsPDF is not defined

php - Doctrine 2 leftJoin, with, manytomany 关系,返回的行数错误

regex - 为什么是s/^\s+|\s+$//g;比两个单独的替换慢得多?

java - 向正则表达式添加长度约束

php - 在 PHP 中安全地捕获 'Allowed memory size exhausted' 错误

php - 构建一个 PHP 路由器

python - 正则表达式捕获字符串的两个部分

javascript - childNodes - 元素内的空白