PHP program to check if a string has a special character

In PHP, you can check if a string contains special characters using regular expressions with the preg_match() function. This is useful for input validation, password strength checking, or data sanitization.

Example

The following example demonstrates how to check for special characters in a string −

<?php
    function check_string($my_string){
        $regex = preg_match('/[@_!#$%^&*()<>?\/|}{~:]/', $my_string);
        if($regex)
            print("String has special characters");
        else
            print("String has no special characters");
    }
    
    $my_string = 'This_is_$_sample!';
    check_string($my_string);
?>

Output

String has special characters

How It Works

The check_string() function uses preg_match() to search for any special characters defined in the regular expression pattern. The pattern /[@_!#$%^&*()<>?\/|}{~:]/ matches common special characters including underscore, dollar sign, exclamation mark, and others.

When preg_match() finds a match, it returns 1 (true), otherwise it returns 0 (false). The function then displays an appropriate message based on whether special characters were found.

Multiple Test Cases

Here's an example testing multiple strings −

<?php
    function check_special_chars($string){
        return preg_match('/[@_!#$%^&*()<>?\/|}{~:]/', $string);
    }
    
    $test_strings = [
        'Hello World',
        'Hello_World!',
        'user@domain.com',
        'SimpleText'
    ];
    
    foreach($test_strings as $str){
        echo "String: '$str' - ";
        echo check_special_chars($str) ? "Has special chars" : "No special chars";
        echo "<br>";
    }
?>

Output

String: 'Hello World' - No special chars
String: 'Hello_World!' - Has special chars
String: 'user@domain.com' - Has special chars
String: 'SimpleText' - No special chars

Conclusion

Using preg_match() with a character class pattern is an effective way to detect special characters in strings. You can customize the pattern to include or exclude specific characters based on your validation requirements.

Updated on: 2026-03-15T09:08:32+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements