Check if String Contains Special Characters in PHP

This tutorial will discuss how to check if string contains special characters in PHP.

To check if a string contains any Special Character in PHP, we can utilize regular expressions.

The regex pattern that we can use is as follows,

'/[^a-zA-Z0-9s]/'

By passing this regex pattern and the string to the preg_match() function, we can determine if the given string contains any Special Character. If preg_match() returns 1, it means that the string contains any Special Character.

We have created a separate function,

function hasSpecialCharacters($strValue)
{
    return preg_match('/[^a-zA-Z0-9s]/', $strValue) === 1;
}

It accepts a string as an argument and returns true if the string contains any Special Character in it. The function internally uses the preg_match() function with the provided regex pattern to perform the check.

Let’s see the complete example,

<?php
/**
 * Check if a string contains special characters.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string contains special characters, false otherwise.
 */
function hasSpecialCharacters($strValue)
{
    return preg_match('/[^a-zA-Z0-9s]/', $strValue) === 1;
}

$strValue = 'This string contains @ special characters!';

// Check if string has some special characters
if (hasSpecialCharacters($strValue)) {
    echo "The string contains special characters.";
} else {
    echo "The string does not contain special characters.";
}
?>

Output

The string contains special characters.

Summary

Today, we learned how to check if string contains special characters 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