0

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
}
WorkarP
  • 57
  • 5
  • To be able to define such a function you first would have to define what you actually consider a "special character" and what not. Why do you think some characters are "special"? They are all characters, none of them are somehow "special". – arkascha Dec 15 '18 at 14:20
  • 1
    The typical motivation for the always returning questions of this type point towards an issue with what you want to do with the treated strings. Typically this is about code not being as robust as it should be... Wouldn't it make more sense to solve the actual cause of the issue instead of trying to cure the symptom as you apparently try to? – arkascha Dec 15 '18 at 14:29

1 Answers1

3

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • You can add underscore as valid character I think in the regexp – Shim-Sao Dec 15 '18 at 14:19
  • @Shim-Sao It isn't completely clear I guess what is being whitelisted here and what is being blacklisted. My answer is my best guess lacking any other information. – Tim Biegeleisen Dec 15 '18 at 14:22
  • I know, more informations are needed., this kind of methods are often use to clear path it's why _ can be correct (for me). – Shim-Sao Dec 15 '18 at 14:26