简体   繁体   English

preg_match不接受新行

[英]preg_match doesn't accept new lines

I know it sounds a little strange, but I'll try to explain. 我知道这听起来有点奇怪,但我会试着解释一下。
use this code to check if $text contains unsupported characters: 使用此代码检查$text包含不受支持的字符:

if(!preg_match('/\A[\w .,]+\z/', $text))
{
    echo "Text contains unsupported characters.";
}

Now the problem is that $text is the text entered by the user in textarea. 现在问题是$text是用户在textarea中输入的文本。

$text_c = $_POST['text'];
$text = mysql_real_escape_string($text_c);
echo "<form method='post'><textarea name='text'>".$text."</textarea><br /><input type='submit' name='submit' value='Submit'></form>";

Everything works perfectly, except one thing. 除了一件事,一切都很完美。 Example, if this is text entered in textarea: 例如,如果这是在textarea中输入的文本:

Hello, my name is John. 你好,我的名字是约翰。

OK. 好。

Hello, my name is John. 你好,我的名字是约翰。
I am 20 years old. 我20岁了。

NO. 没有。 Text contains unsupported characters. 文本包含不受支持的字符。 (refers to the new line, because content of the textarea change and have something like: My name is John.\\r\\nI am 20 years old. ) (指的是新行,因为textarea的内容发生了变化,并且有类似的东西: My name is John.\\r\\nI am 20 years old.

My question is: what I need to change to support new lines? 我的问题是:我需要改变什么以支持新线路? I hope you understand. 我希望你明白。

EDIT: I just discovered, without mysql_real_escape_string everything works exactly as I want. 编辑:我刚刚发现,没有mysql_real_escape_string一切都按照我想要的方式工作。 Is there any solution to "combine" mysql_real_escape_string with preg_match (in my case) or mysql_real_escape_string supposed to drop? 是否有任何解决方案将mysql_real_escape_stringpreg_match (在我的情况下)或mysql_real_escape_string “结合” mysql_real_escape_string

You can use \\s to represent whitespace (new lines, tabs and spaces). 您可以使用\\s来表示空格(新行,制表符和空格)。

So your regex becomes: /\\A[\\w .,\\s]+\\z/ 所以你的正则表达式变成: /\\A[\\w .,\\s]+\\z/

Note \\n \\r are both valid escape characters and \\r\\n together will match a dos line break if you don't want to include spaces/tabs. 注意\\n \\r是两个有效的转义字符,如果您不想包含空格/制表符, \\r\\n将匹配dos换行符。

Good reference: http://www.regular-expressions.info/reference.html 好参考: http//www.regular-expressions.info/reference.html

It's not the same error; 这不是同一个错误; rather, it's not erroring for the same reason you think it is. 相反,它不会因为您认为的原因而出错。
It's not the newlines that are tripping your regex up, it's the numbers. 这不是让你的正则表达式绊倒的新行,而是数字。 ;-) ;-)
Add \\d to your regex as well: /\\A[\\w\\d\\s.,]+\\z/ 将\\ d添加到你的正则表达式: /\\A[\\w\\d\\s.,]+\\z/ \\ /\\A[\\w\\d\\s.,]+\\z/

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

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