preg_match special characters

My function makes life easier.

function has_specchar($x,$excludes=array()){
    if (is_array($excludes)&&!empty($excludes)) {
        foreach ($excludes as $exclude) {
            $x=str_replace($exclude,'',$x);        
        }    
    }    
    if (preg_match('/[^a-z0-9 ]+/i',$x)) {
        return true;        
    }
    return false;
}

The second parameter ($excludes) may be passed with values you wish to ignore.

Usage

$string = 'testing_123';
if (has_specchar($string)) { 
    // special characters found
} 

$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false

Use preg_match. This function takes in a regular expression (pattern) and the subject string and returns 1 if match occurred, 0 if no match, or false if an error occurred.

$input = 'foo';
$pattern = '/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';

if (preg_match($pattern, $input)){
    // one or more matches occurred, i.e. a special character exists in $input
}

You may also specify flags and offset for the Perform a Regular Expression Match function. See the documentation link above.


[\W]+ will match any non-word character.

but to match only the characters from the question, use this:

  $string="sadw$"
  if(preg_match("/[\[^\'£$%^&*()}{@:\'#~?><>,;@\|\\\-=\-_+\-¬\`\]]/", $string)){
   //this string contain atleast one of these [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`] characters
  }

For me, this works best:

$string = 'Test String';

$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';

$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
   // string contains one or more of the characters in var $blacklistChars
}

Tags:

Php