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:


$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?

Edited by Aeonix

10 Months
Discussion Span
Last Post by pritaeas

Your pattern checked only first character. Change to:
(!preg_match("/^[0-9a-zA-Z ]+$/", $name3))

Edited by AndrisP

Votes + Comments

The following should match:

/[\w ]+/


/^[\w ]+$/

You are missing a repeater, so your regex only checks the first character (J). The regex above matches one or more word characters or a space.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.