Page 1 of 1

preg_match how to check if string contains special chars

Posted: Tue Jan 26, 2010 11:17 pm
by Hieroglyphics
How do I use preg_match to find out if a string contains special chars like `~!@#$%^&*()-_=+[{]}\|'";:.>,</?

I did: preg_match('#[^a-zA-Z0-9]#', $string)

but that doesn't include # and &

Re: preg_match how to check if string contains special chars

Posted: Wed Jan 27, 2010 9:28 am
by social_experiment

Code: Select all

 
<?php
 $pattern = '/~!@#\$%\^&\*\(\)-_=\+\[\{\]\}/';
?>
 
Matches up to } within your string, for the other i broke them down in things like :

Code: Select all

 
<?php
    $pattern1 = '/\|/';    
    $pattern2 = '/;/';    
    $pattern3 = '/\'/';    
    $pattern4 = '/"/';
    $pattern5 = '/;/';    
    $pattern6 = '/:/';    
    $pattern7 = '/./';
?>
 
Im not sure how implementation will work if you wished to test a string for all of the characters. :?:

Re: preg_match how to check if string contains special chars

Posted: Wed Jan 27, 2010 9:55 am
by requinix
It's smarter to check for characters you do want.
Hieroglyphics wrote:I did: preg_match('#[^a-zA-Z0-9]#', $string)

but that doesn't include # and &
Yes it does.

Code: Select all

if (preg_match('#[^a-zA-Z0-9]#', $string)) {
    // $string has at least one character that is not a letter or number
} else {
    // $string is entirely letters and numbers
}
And for the record, there's no point using regular expressions when there are functions that specifically do this already.

Re: preg_match how to check if string contains special chars

Posted: Wed Jan 27, 2010 9:57 am
by AbraCadaver
Hieroglyphics wrote:How do I use preg_match to find out if a string contains special chars like `~!@#$%^&*()-_=+[{]}\|'";:.>,</?

I did: preg_match('#[^a-zA-Z0-9]#', $string)

but that doesn't include # and &
I don't understand. Your pattern only matches NOT letters and numbers. By the list of characters you gave, I thought that's what you want? It matches any of these: `~!@#$%^&*()-_=+[{]}\|'";:.>,</?