check if you have ctype support.
now $text is the string we gonna evaluate:
// Strip whitespace from the beginning and end of a string
$text = trim($text)
if (!ctype_space($text)) { // text don't have any spaces
if(ctype_alnum($text)) {
// text is alphanumeric, everything is OK.
}
elseif (substr_count($text, "_") > 0) {
// text is NOT alphanum and have at least 1 underscore
$pieces = explode("_", $text);
// now we check if the pieces are alphanumeric (separated by _)
for($i = 0; $i < count($pieces); $i++) {
// we made an array of error codes, 0 if the piece is alphanum, and 1 if NOT.
if(ctype_alnum($pieces[$i]) $error[$i] = 0; else $error[$i] = 1;
}
if(in_array("1", $error)) { echo "ERROR: Please insert an alphanumeric value (can contain underscores)";
} else {
// EVERYTHING IS OK.
}
} else {
echo "ERROR: Please insert an alphanumeric value (can contain underscores)";
}
}