简体   繁体   中英

Check if a strings has special characters except hyphen?

How do I check if a strings has special characters except hyphen?

Example:

$str1 = "what?"; 
has_special_characters_except_hyphen($str1); // should return true

$str2 = "whats-up"; 
has_special_characters_except_hyphen($str2); // should return false

function has_special_characters_except_hyphen($str) {
     // check for special characters except hyphen
}

One option uses preg_match with the pattern [^A-Za-z0-9-] :

$str1 = "what?";
if (preg_match("/[^A-Za-z0-9-]/", $str1)) {
    echo "YES";
}

This would print YES should there be at least one character in $str1 which is not alphanumeric or hyphen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM