frshjb373 Posted April 29, 2012 Share Posted April 29, 2012 I'm trying to write a script to validate a legal php variable name, but I can't seem to make it work so it doesn't validate spaces. Any help would be much appreciated! Here's my code: <fieldset><legend><h1>PHP Variable Validator</h1></legend> <p>A valid PHP variable begins with the dollar sign ("$") followed by either a letter or underscore ("_") followed by any series of numbers, letters or underscores.</p> <p>Ex: $variable</p> <form action="name_validator.php" method="post"> <input name="variable" type="text" /> <input name="submit" type="submit" value="Validate it!" /> </form> <?php $variable = $_POST['variable']; if ($variable == "quit") { echo "Thanks for trying the validator!"; } elseif (preg_match("/^[$][a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/",$variable)) { echo "<b>" . $variable . "</b>" . " is a valid PHP variable name"; } elseif (!isset($variable)) { echo ""; } else { echo "<b>" . $variable . "</b>" . " is not a valid PHP variable name"; } ?> </fieldset> Link to comment https://forums.phpfreaks.com/topic/261789-validate-user-entry-to-have-no-spaces/ Share on other sites More sharing options...
requinix Posted April 29, 2012 Share Posted April 29, 2012 You need a $ anchor to ensure the expression matches the entire string, rather than just an initial length of it. Link to comment https://forums.phpfreaks.com/topic/261789-validate-user-entry-to-have-no-spaces/#findComment-1341488 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.