Jason12
Jason12

Reputation: 369

PHP Regular expressions -- character class

I would like to know something about the PHP character class which I believe I do not yet fully understand. Let us take this snippet of code from w3schools.com:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
    $nameErr = "name is required";
    } else {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $name = "";
            $nameErr = "Only letters and white space allowed";
        }
    }
}

Let's say that the asterisk next to the closing square bracket of the third "if" condition did not exist. In other words, you would not have "zero or more times", but simply "once".

My question is then:

I cannot test it out on w3schools.com because the source code cannot be changed by the viewer. I am instead using an online regex checker http://www.regexr.comand -- when I enter the code "/([a-zA-Z])/" and test it against the string Jason, ALL the characters match! This shouldn't be the case. I SHOULD get a false.

Upvotes: 0

Views: 128

Answers (2)

Gustav Bertram
Gustav Bertram

Reputation: 14911

The ^ marker indicates "start of the string", and $ indicates "end of the string".

Removing the asterisk means "Jason" will not match, but "J" will.

You can find the reference for the PCRE regular expression patterns in the PHP manual.

If you can't run code locally to test it, you can still run a snippet in PHP Fiddle. I suggest you play with the example patterns in the manual.

Upvotes: 1

Álvaro González
Álvaro González

Reputation: 146460

If you remove the ^ and $ markers your rule says "has a letter somewhere". Jason fulfils that.

Upvotes: 1

Related Questions