preg_match how to check if string contains special chars

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Hieroglyphics
Forum Newbie
Posts: 13
Joined: Wed Jan 20, 2010 8:25 pm

preg_match how to check if string contains special chars

Post 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 &
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: preg_match how to check if string contains special chars

Post 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. :?:
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: preg_match how to check if string contains special chars

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: preg_match how to check if string contains special chars

Post 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: `~!@#$%^&*()-_=+[{]}\|'";:.>,</?
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply