This function will check for alpha-numeric charaters, the tilde, carrot, underscore, hyphen and period. All other characters are invalid
<?
function Validate_String($string, $return_invalid_chars)
{
$valid_chars = "1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$invalid_chars = "";
if($string == null || $string == "")
return(true);
//For every character on the string.
for($index = 0; $index < strlen($string); $index++)
{
$char = substr($string, $index, 1);
//Is it a valid character?
if(strpos($valid_chars, $char) === false)
{
//If not, is it already on the list of invalid characters?
if(strpos($invalid_chars, $char) === false)
{
//If it's not, add it.
if($invalid_chars == "")
$invalid_chars .= $char;
else
$invalid_chars .= ", " . $char;
}
}
}
//If the string does not contain invalid characters, the function will return true.
//If it does, it will either return false or a list of the invalid characters used
//in the string, depending on the value of the second parameter.
if($return_invalid_chars == true && $invalid_chars != "")
{
$last_comma = strrpos($invalid_chars, ",");
if($last_comma != false)
$invalid_chars = substr($invalid_chars, 0, $last_comma) .
" and " . substr($invalid_chars, $last_comma + 1, strlen($invalid_chars));
return($invalid_chars);
}
else
return($invalid_chars == "");
}
?>
NOTE: This is how to call it. (the form test.php calls itself also)
<?php if ($submit ==""){ ?>
<form action="test.php" method="post">
<table>
<tr><td>Your name:</td><td>
<input type="text" name="name"></td></tr>
</table> <br>
<input type="submit" name="submit" value="submit">
</form>
<?php }else {
$results = Validate_String($name);
if ($results == 1) {
echo "string is valid"; }
else{ echo "invalid string";}
}?>