【问题标题】:Checking for new lines in a string检查字符串中的新行
【发布时间】:2012-04-01 08:52:49
【问题描述】:

谁能告诉我为什么这不起作用?它总是返回false

$str = "huuhhu\r\n\r\nmoo.com\r\nwww";

if (preg_match('/(\\n|\\r\\n|\\r)/', $str) === true) {
    echo "True";
} else {
    echo "False";
}

【问题讨论】:

  • 请注意:您不需要正则表达式的双转义,因为您使用的是单引号。 '/(\n|\r\n|\r)/' 也可以。

标签: php regex preg-match newline


【解决方案1】:

preg_match 不返回 true。它返回匹配的数量。你需要这样做:

$str = "huuhhu\r\n\r\nmoo.com\r\nwww";

if (preg_match('/(\\n|\\r\\n|\\r)/', $str)) {
    echo "True";
} else {
    echo "False";
}

另外,您可以将表达式简化为:

'/\n|\r\n?/'

【讨论】:

  • 对不起 php n00b 在这里,但是 if(0) 在 php 中肯定是假的,如果 (1),if(2),if(3) 等在几乎任何其他语言中都是真的?
  • 是的。但是使用=== 也会考虑type,并且integerboolean 的类型不同。如果您愿意,可以使用== true,但这与忽略所有内容相同。
【解决方案2】:

preg_match() 返回模式匹配的次数,如果发生错误则返回FALSE。它永远不会返回true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    相关资源
    最近更新 更多