I know it sounds a little strange, but I'll try to explain.
use this code to check if $text
contains unsupported characters:
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_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:
Hello, my name is John.
OK.
Hello, my name is John.
I am 20 years old.
NO. Text contains unsupported characters. (refers to the new line, because content of the textarea change and have something like: My name is John. I 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. Is there any solution to "combine" mysql_real_escape_string
with preg_match
(in my case) or mysql_real_escape_string
supposed to drop?
You can use \s
to represent whitespace (new lines, tabs and spaces).
So your regex becomes: /\A[\w .,\s]+\z/
Note
are both valid escape characters and
together will match a dos line break if you don't want to include spaces/tabs.
Good reference: 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/