Check if a string contains special characters in PHP

This tutorial will discuss about a unique way to check if a string contains special characters in php.

We can use the regular expression to check if string contains any special character in PHP.

The regex pattern ‘/[^a-zA-Z0-9\s]/’ matches a string that contains at least a character which is not a letter or number or a white space character. If it returns 1, then it means this string has a special character in it.

So, we can use this regex pattern with the preg_match function() to check if string contains a special character.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains special characters
 * using regular expressions (preg_match()).
 *
 * @param string $str The string to check.
 * @return bool True if the string contains special characters, false otherwise.
 */
function containsSpecialCharacters($str)
{
    return preg_match('/[^a-zA-Z0-9\s]/', $str) === 1;
}

$strValue = "Last Coder!";

if (containsSpecialCharacters($strValue)) {
    echo "The string contains special characters.";
} else {
    echo "The string does not contain special characters.";
}
?>

Output

The string contains special characters.

There is an another way using the regular expression to check if string contains any special character in PHP. For that we will use this regex pattern,

'/[\'^£$%&*()}{@#~?><>,|=_+¬-]/'

It matches a string which contains any character from this provided list of special characters. If it returns 1, then it means this string has a special character in it.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains special characters
 * using regular expressions (preg_match()).
 *
 * @param string $str The string to check.
 * @return bool True if the string contains special characters, false otherwise.
 */
function containsSpecialChars($str)
{
    return preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $str) === 1;
}

// Example usage:
$strValue = "Last Coder!";
if (containsSpecialChars($strValue)) {
    echo "The string contains special characters.";
} else {
    echo "The string does not contain special characters.";
}
?>

Output

The string does not contain special characters.

Summary

Today, we learned about 2 different ways to check if string contains at least a special character in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top