phpdragon Posted June 4, 2009 Share Posted June 4, 2009 I am just trying to check the $username input of the form in the code below to make sure it only has the characters a-z, A-Z, 0-9, _, - and nothing more, if it contains a character outside those parameters I just want to spit out and error message with the variable $badchars containing the illegal chars. What I have below is not quite what I have asked for, so I would like some help modifying it to work that way. I <?php if (isset($_POST['submit'])) { $username=$_POST['username']; if (preg_match('#[^a-z0-9]#i', $username > 0)) { $error="<font color='red'>$username contains unacceptable ( $badchars ) characters</font>"; } else { $error="<font color='green'>$username checks out fine</font>"; } } if (isset($error)) { echo $error; } ?> <br/> <form name="test" action="nasty.php" target="_self" method="post"> <input type="text" size="20" name="username" value="<?php if (isset($username)) { echo $username; } ?>" /> <input type="submit" name="submit" value="check" /> </form> Link to comment https://forums.phpfreaks.com/topic/160885-solved-search-for-characters-in-a-string/ Share on other sites More sharing options...
JasonLewis Posted June 4, 2009 Share Posted June 4, 2009 Something like this? $username = "this@has!badchars%"; if(preg_match("#[^\w\d_-]#i", $username)){ echo "Bad"; }else{ echo "Good"; } Link to comment https://forums.phpfreaks.com/topic/160885-solved-search-for-characters-in-a-string/#findComment-849068 Share on other sites More sharing options...
phpdragon Posted June 4, 2009 Author Share Posted June 4, 2009 if(preg_match("#[^\w\d_-]#i", $username)){ echo "Bad ($char)"; }else{ echo "Good"; } That bit works great thank you. In the "Bad" Section how would I echo the first bad character or even all bad characters that were input from $username as $char for example? Link to comment https://forums.phpfreaks.com/topic/160885-solved-search-for-characters-in-a-string/#findComment-849087 Share on other sites More sharing options...
phpdragon Posted June 4, 2009 Author Share Posted June 4, 2009 if(preg_match("#[^\w\d_-]#i", $username, $char)){ if ($char[0]==" ") { $char[0]="no spaces"; } echo "Bad (".$char[0].")"; }else{ echo "Good"; } This solved the problem for me Link to comment https://forums.phpfreaks.com/topic/160885-solved-search-for-characters-in-a-string/#findComment-849113 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.