Open In App

PHP to Check if a String Contains any Special Character

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, the task is to check whether a string contains any special characters in PHP. Special characters are characters that are not letters or numbers, such as punctuation marks, symbols, and whitespace characters.

Examples:

Input: str = "Hello@Geeks"
Output: String contain special characters.

Input: str = "GeeksforGeeks"
Output: String does not contain special characters.

These are the following approaches:

Approach 1: Using Regular Expressions

One of the most efficient method to check for special characters in a string is by using regular expressions with the preg_match() function. the custom specialChars() function uses the preg_match() function to check if the input string contains any character that is not a letter (a-z A-Z) or a number (0-9). The regular expression /[^a-zA-Z0-9]/ matches any character that is not in the specified range. If preg_match() returns a value greater than 0, it means that the string contains special characters.

Example: This example shows if any special character present in the given string or not using regular expression.

PHP
<?php
function specialChars($str) {
    return preg_match('/[^a-zA-Z0-9]/', $str) > 0;
}

$str = "Hello@Geeks";

if (specialChars($str)) {
    echo "String contain special characters.";
} else {
    echo "String does not contain special characters.";
}

?>

Output
String contain special characters.

Approach 2: Using ctype_alnum() Function

Another method to check for special characters in a string is by using the ctype_alnum() function, which checks if all characters in a string are alphanumeric (letters and numbers). the specialChars() function uses the ctype_alnum() function to check if the input string is alphanumeric. If the string is not alphanumeric, it means that it contains special characters. The function returns true if special characters are found and false otherwise.

Example: This example shows if any special character present in the given string or not using ctype_alnum() Function.

PHP
<?php

function specialChars($str) {
    return !ctype_alnum($str);
}

$str = "Hello@Geeks";

if (specialChars($str)) {
    echo "String contain special characters.";
} else {
    echo "String does not contain special characters.";
}

?>

Output
String contain special characters.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads