hillz hillz - 1 year ago 72
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 ?


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

Answer Source

This regex should work:

  • \s matches all whitespaces including newline
  • Keep unescaped hyphen at first or last position in a character class

RegEx Demo


if (preg_match('/^[A-Za-z0-9=.,:\s-]+$/', file_get_contents($filename))) {
    echo "it matches";
else {
    echo "doesn't match";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download