user3766078
user3766078

Reputation: 91

PHP regex to allow newline didn't work

PHP preg_match to accept new line

I want to pass every post/string through PHP preg_match function. I want to accept all the alpha-numerics and some special characters. Help me edit my syntax to allow newline. As the users fill textarea and press enter. Following syntax does not allow new line.

Please feedback whether following special characters are properly done or not */_:,.?@;-*

if (preg_match("/^[0-9a-zA-Z \/_:,.?@;-]+$/", $string)) { 
    echo 'good';
else {
    echo 'bad';
}

Upvotes: 3

Views: 2012

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173662

You can use an alternation to factor in the newlines:

/^(?:[0-9a-zA-Z \/_:,.?@;-]|\r?\n)+$/

Btw, you can shorten the expression a bit by replacing [A-Za-z0-9_] with [\w\d]:

/^(?:[\w\d \/:,.?@;-]|\r?\n)+$/

So:

if (preg_match('/^(?:[\w\d \/:,.?@;-]|\r?\n)+$/', $string)) {
    echo "good";
} else {
    echo "bad";
}

Upvotes: 0

zx81
zx81

Reputation: 41848

You were almost there!

The DOTALL modifier mentioned by others is irrelevant to your regex.

To allow new lines, we just add \r\n to your character class. Your code becomes:

if (preg_match("/^[\r\n0-9a-zA-Z \/_:,.?@;-]+$/", $string)) { 
    echo 'good';
else {
    echo 'bad';
}

Note that this test and the regex can be written in a tidier way:

echo (preg_match("~^[\r\n\w /:,.?@;-]+$~",$string))? "***Good!***" : "Bad!";

See the result of the online demo at the bottom.

  • \w matches letters, digits and underscores, so we can get rid of them in the character class
  • Changing the delimiter to a ~ allows you to use a / slash without escaping it (you need to escape delimiters)

Upvotes: 5

albertdiones
albertdiones

Reputation: 733

it's always safe to add backslash to any non-alphanumeric characters so:

/^[0-9a-zA-Z \/\_\:\,\.\?\@\;\-]+$/

Also use character classes:

/^[[:alnum:] \/\_\:\,\.\?\@\;\-]+$/

oh about the new lines:

/^[[:alnum:] \r\n\/\_\:\,\.\?\@\;\-]+$/

to be able to do that string ^ (also, it'll be easier/safer to use single quotes)

'/^[[:alnum:] \\r\\n\/\_\:\,\.\?\@\;\-]+$/'

Upvotes: 0

Related Questions