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 &
preg_match how to check if string contains special chars
Moderator: General Moderators
-
Hieroglyphics
- Forum Newbie
- Posts: 13
- Joined: Wed Jan 20, 2010 8:25 pm
- 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
Code: Select all
<?php
$pattern = '/~!@#\$%\^&\*\(\)-_=\+\[\{\]\}/';
?>
Code: Select all
<?php
$pattern1 = '/\|/';
$pattern2 = '/;/';
$pattern3 = '/\'/';
$pattern4 = '/"/';
$pattern5 = '/;/';
$pattern6 = '/:/';
$pattern7 = '/./';
?>
“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
Re: preg_match how to check if string contains special chars
It's smarter to check for characters you do want.
And for the record, there's no point using regular expressions when there are functions that specifically do this already.
Yes it does.Hieroglyphics wrote:I did: preg_match('#[^a-zA-Z0-9]#', $string)
but that doesn't include # and &
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
}- 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
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: `~!@#$%^&*()-_=+[{]}\|'";:.>,</?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 &
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.