I want to check for illegal characters, only A-Z are allowed. But my code does not work. Is this the right way to do it?
if (preg_match('/^[A-Z]/', 'QWERTY') == 1)
{
// contains valid characters
}
else
{
// error
}
I want to check for illegal characters, only A-Z are allowed. But my code does not work. Is this the right way to do it?
if (preg_match('/^[A-Z]/', 'QWERTY') == 1)
{
// contains valid characters
}
else
{
// error
}
if (preg_match('/^[A-Z]/', 'QWERTY') == 1)
You have your square brackets in the wrong position
Also preg_match returns true/false so you do not need the ==1 at the end(like substr).
Cleaned code:
if(preg_match('/[^A-Z]/', 'QWERTY'))
{
// contains valid characters
}
else
{
// error
}
neilmasters;10964704 wrote:
if (preg_match('/^[A-Z]/', 'QWERTY') == 1)
if(preg_match('/[^A-Z]/', 'QWERTY')) { // contains valid characters } else { // error }
Except that you also need to change either the comparison or the if- and else-blocks.
That is, either
if(preg_match('/[^A-Z]/', 'QWERTY') == false)
or
if(preg_match('/[^A-Z]/', 'QWERTY'))
{
// error
}
else
{
// contains ONLY valid characters
}
Thanks for the great answers, it works now and I have learned a lot.
vigour;10964793 wrote:I want to check if there are 2 or more spaces in a row, how do I modify my code so it wont allow that? Or even better, take away all but 1 space automatically?
Use this to replace multiple whitespaces with a single one in each place. But do note that \s matches any whitespace character, such as new line, horizontal tab etc. Thus
$string = "A B
C";
$string = preg_replace('/(\s)+/', '\1', $string);
Gives
A B
C
If you only want to allow the ordinary space character, then use that instead of \s
^/[A-Za-z0-9 ]$/
And the replacement would no longer need a back reference
$string = preg_replace('/ +/', ' ', $string);