How to check if a string contains only letters, numbers, underscores and dashes in PHP

1 Answer

0 votes
function isValidString($s) {
    $pattern = '/^[A-Za-z0-9_-]*$/';
    
    return preg_match($pattern, $s);
}

$s1 = "-abc_123-";
echo isValidString($s1) ? "yes\n" : "no\n";

$s2 = "-abc_123-(!)";
echo isValidString($s2) ? "yes\n" : "no\n";


  
/*
run:
  
yes
no
 
*/

 



answered May 31, 2025 by avibootz
...