I've been Googling this one, and I've come across solutions, but they don't seem to work for me. The code is as follows:
<?php
$name1 = "Jack Random"; // true
$name2 = "JackRandom"; // true
$name3 = "Jack;Random"; // false
$name4 = "JackRand;om"; // false
// Accept only A-Z, a-z, 0-9 and space.
if (!preg_match("/^[0-9a-zA-Z ]/", $name1)) echo "Nope, not good";
echo "<br />";
if (!preg_match("/^[0-9a-zA-Z ]/", $name2)) echo "Nope, not good";
echo "<br />";
if (!preg_match("/^[0-9a-zA-Z ]/", $name3)) echo "Nope, not good";
echo "<br />";
if (!preg_match("/^[0-9a-zA-Z ]/", $name4)) echo "Nope, not good";
// Tried: /^[0-9a-zA-Z ]/
// Tried: [^a-zA-Z0-9\s]
// Tried: /\\w|\\s+/
// Tried: ^[A-Za-z0-9 ]+$ (error, missing delimiter)
?>
First and second should return true, and third and fourth should return false.
The thing is that to every provided RegEx, they respond in the same way.
They're all error, or none of them.
I could've always put !
to flip them to correct working, but they don't differentiate.
The one that I thought would work is: /^[0-9a-zA-Z ]/
, but nah. Why would it
be easy?