简体   繁体   English

PHP正则表达式不是新行

[英]PHP regex not new line

How do I have a regex statement that accepts any character except new lines. 如何使用接受除新行之外的任何字符的正则表达式语句。 This includes anything but also includes new lines which is not what i want: 这包括任何东西,但也包括新的行,这不是我想要的:

"/(.*)/"

The dot . . does not match newlines unless you use the s modifier. 除非使用s修饰符,否则与换行符不匹配。

>>> preg_match("/./", "\n")
0
>>> preg_match("/./s", "\n")
1

As written on the PHP Documentation page on Preg Modifiers, a dot . 正如在Preg Modifiers上的PHP Documentation页面上所写的那样. does NOT include newlines, only when you use the s modifier. 仅当您使用s修饰符时才包含换行符。 Source 资源

以下正则表达式应匹配除换行符之外的任何字符

/[^\n]+/

The default behavior shouldn't match a new line. 默认行为不应与新行匹配。 Because the "s" modifier is used to make the dot match all characters, including new lines. 因为“s”修饰符用于使点匹配所有字符,包括新行。 Maybe you can provide an example to look at? 也许你可以提供一个例子来看看?

#!/usr/bin/env php
<?php

$test = "Some\ntest\nstring";

// Echos just "Some"
preg_match('/(.*)/', $test, $m);
echo "First test: ".$m[0]."\n";

// Echos the whole string.
preg_match('/(.*)/s', $test, $m);
echo "Second test: ".$m[0]."\n";

So I don't know what is wrong with your program, but it's not the regex (unless you have the /s modifier in your actual application. 所以我不知道你的程序有什么问题,但它不是正则表达式(除非你的实际应用程序中有/s修饰符。

this is strange, because by default the dot (.) does not accept newlines. 这很奇怪,因为默认情况下,点(。)不接受换行符。 Most probably you have a "\\r" (carriage return) character there, so you need to eliminate both: /[^\\r\\n]/ 很可能你有一个“\\ r”(回车)字符,所以你需要消除两者: /[^\\r\\n]/

ah, you were using /s 啊,你用的是/ s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM