hillz hillz - 1 month ago 10
PHP Question

How to match letters, numbers and new lines with regex?

I have this text file:

Host: x-sgdo40.serverip.co
Username: fastssh.com-test
Password: test
Port: 443
Info: Date Expired : 10-November-2016


I want to match that with letters, numbers, some additional characters and new lines:

if (preg_match("/^[A-Za-z0-9 =.,:-]+$/",file_get_contents($filename))){
echo "it matches";
}
else {
echo "doesn't match";
}


The problem is that
/^[A-Za-z0-9 =.,:-]+$/
doesn't match new lines, how can I fix this ?

EDIT:

^[A-Za-z0-9 =.,:\\n-]+$
still doesn't work

Answer

This regex should work:

^[A-Za-z0-9=.,:\s-]+$
  • \s matches all whitespaces including newline
  • Keep unescaped hyphen at first or last position in a character class

RegEx Demo

Code:

if (preg_match('/^[A-Za-z0-9=.,:\s-]+$/', file_get_contents($filename))) {
    echo "it matches";
}
else {
    echo "doesn't match";
}