How can I only allow the characters W, L, and D in a string? I have written this
if ((strpos($input, 'w') === false)
&& (strpos($input, 'd') === false)
&& (strpos($input, 'l') === false)) {
$answer = "FALSE";
} else {
$answer = "TRUE";
}
but this only works if all the characters are W, L, D or none of the characters are W, L or D. I cant work out how to get it to spot when just some of the characters are incorrect.
eg
wwwlld = TRUE (correct)
12aab6 = FALSE (correct)
www44d = TRUE (incorrect, this needs to be FALSE as it contains '44')
Any help much appreciated.
P
This is a classic example of requiring regular expressions, which are the preg_match function in PHP.
You probably want to use something like the following
$pattern = '/^[wdl]*$/';
This would only match a string where between the start and the end of the string, 0 or more characters in the set w, d or l.
You can use regular expressions for this using the pattern ^[wdl]+$
:
$values = array('wwwlld', '12aab6', 'www44d');
foreach($values as $value)
{
echo $value;
if (preg_match('/^[wdl]+$/', $value))
echo " = TRUE
";
else
echo " = FALSE
";
}
Output of the above:
wwwlld = TRUE
12aab6 = FALSE
www44d = FALSE
Online demo here.
$subject = "wwwlld";
preg_match('/^[wdl]+$/', $subject, $matches);
echo ($matches) ? 'TRUE' : 'FALSE';
Output:
//wwwlld = TRUE
//12aab6 = FALSE
//www44d = FALSE