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?

Recommended Answers

All 2 Replies

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

commented: Yea! +4

The following should match:

/[\w ]+/

or:

/^[\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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.