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> Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.