Checking a PHP string for valid characters

How can I check if a string contains only numbers, letters, -, or _ (no spaces or other characters?


Answer 1, authority 100%

<?php
$str = ' ';
if (preg_match("#^[aA-zZ0-9\-_]+$#",$str)) {
   echo " ";
} else {
   echo "  ";
}
?>

Somehow.


Answer 2, authority 25%

The answer above is not working

$str = 'string to check';
if (preg_match("/^[a-zA-Z0-9\-_]+$/")) {
echo '    (: a-z, A-Z, 0-9, -, _)';
}
//https://regex101.com/r/sOqk8P/1
$str = 'string to check';
if (preg_match("/[^a-zA-Z0-9\-_]+/")) {
echo '   (  , : a-z, A-Z, 0-9, -, _)';
}
//https://regex101.com/r/lY0846/1
//     - ,   ""     -,   "":
$str = '    ';
if (preg_match("/^[--a-zA-Z0-9\-_]+$/")) {
echo '    (: -, -, a-z, A-Z, 0-9, -, _)';
}
$str = '    ';
if (preg_match("/[^--a-zA-Z0-9\-_]+/")) {
 echo '   (  , : -, -, a-z, A-Z, 0-9, -, _)';
}