I know there are more elegant ways to set up an html form to take the input of male or female; however, I am learning, and I was just wondering if this is also possible:
//Incorpor开发者_开发技巧ate two checks
if (empty($_POST['sex'])==FALSE && sanityCheck($_POST['sex'], 'string', 1)==TRUE)
{
// if the checks are ok for sex we assign sex to a variable
$sex = $_POST['sex'];
}
else
{
// if all is not well we echo an error message
echo 'Please enter a valid Gender';
// and exit the script
exit();
}
If so, how would I check this with regex? Whether the user typed M or F.
I am thinking:
function checksex($sexcheck)
{
//Some regex here to check the sex?
return preg_match(' ', $sexcheck);
}
And then call checksex as a third check added to the if conditional, like this:
if (empty($_POST['sex'])==FALSE && sanityCheck($_POST['sex'], 'string', 1) != FALSE && checksex($_POST['sex'], 1) ==TRUE)
{
...
}
To check if the user typed M or F, all you would need to do is a string comparison. No need for regex
if ( isset($_POST['sex']) ){
$sex = $_POST['sex'];
if ( $sex == 'M' ){
echo 'Male';
}else if ( $sex == 'F' ){
echo 'Female';
}else{
echo 'Please enter a valid Gender';
}
}else{
echo 'Please enter a valid Gender';
}
However, rather than having the user type out M or F, why not use a select box or Radio Buttons ?
A select box may look something like this
<select name='sex'>
<option selected="yes" value="NA">Not Saying</option>
<option value="F">Female</option>
<option value="M">Male</option>
</select>
Or radio buttons:
<input type="radio" name="sex" value="M" /> Male <br />
<input type="radio" name="sex" value="F" /> Female
You would of course still have to check that $_POST['sex']
is still M or F, and handle the case where it isn't either of them, as the user may decide to post an invalid value.
Try this "(M|F){1}" without the quotes
How about
// check if the sex variable is 'f' or 'm'
$sex = ($_POST['sex'] == 'f' || $_POST['sex'] == 'm') ? $_POST['sex'] : false;
// thanks to peter
// if $sex is false then echo..
if (!$sex)
echo ('Please enter a valid Gender');
Explaination
its a conditional operator called Ternary Operator. Its like
(if clause) ? (then) : (else);
Or
(expr 1) ? (expr 2) : (expr 3);
expr 2 is evaluated if expr 1 is true expr 3 is evaluated if expr 1 is false
Ref : http://php.net/manual/en/language.operators.comparison.php
$s = $_POST['sex'];
if(isset($s) && $s == 'M') {
$sex = "Male";
} elseif(isset($s) && $s == 'F') {
$sex = "Female";
} else {
$sex = "Please enter a valid gender";
}
精彩评论