Alexander
Alexander

Reputation: 153

Allow only few characters with preg_match

I want to use preg_match to allow only few characters, more exactly, I want to allow only these characters: a-z A-Z 0-9 . , ( ) @ # ! ?

How can I do that with preg_replace, to check if text contains more than these characters or not?

Upvotes: 1

Views: 5068

Answers (2)

Toto
Toto

Reputation: 91385

In order to test if your sting contains invalid characters, you could do:

if ( preg_match('/[^a-zA-Z0-9.,()@#!?]/', $string) )
    echo 'At least ONE invalid character found!';

I'm not sure I well understand what you want, but here are some regex that you can use:

if ( preg_match('/^[^a-zA-Z0-9.,()@#!?]+$/', $string) )
    echo 'All characters are invalid!';

if ( preg_match('/^[a-zA-Z0-9.,()@#!?]+$/', $string) )
    echo 'All characters are valid!';

Upvotes: 2

m4t1t0
m4t1t0

Reputation: 5721

If you want to remove all characters from a string except the ones you've indicated, you can use:

$sanitized = preg_replace('/[^a-zA-Z0-9\.\,\(\)@#!?]/', '', $string);

Upvotes: 3

Related Questions