preg_match special characters

Viewed 83658

How can I use preg_match to see if special characters [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`] exist in a string?

7 Answers

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.

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
}

This works well for all PHP versions. The resultant is a bool and needs to be used accordingly.

To check id the string contains characters you can use this:

preg_match( '/[a-zA-Z]/', $string );

To check if a string contains numbers you can use this.

preg_match( '/\d/', $string );

Now to check if a string contains special characters, this one should be used.

preg_match('/[^a-zA-Z\d]/', $string);

In case you want to match on special characters

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