new_webmaster
new_webmaster

Reputation: 107

Validate user input string only contains letters, numbers, and underscores

$page = $_GET['page'];
if (isset($page))
    if (!preg_match('/[\w\d_]+/i', $page))
        die("Error");

I want to allow alphanum and underscore.

My above code works, but let say I set 123..., this works too.

Is preg_match() not able to validate trailing characters after the match?

Upvotes: 0

Views: 176

Answers (2)

kennytm
kennytm

Reputation: 523784

The regex will match as long as an alphanumeric appears as a substring of $page. Since 123... contains the substring 123 it will pass your regex.

Use

/^\w+$/

to match the whole string. (\w already means [a-zA-Z0-9_] so your \d, _ and the i modifier are redundant.)

Upvotes: 2

codaddict
codaddict

Reputation: 455460

You need to use anchors as:

/^\w+$/

\w already has \d and _

Upvotes: 0

Related Questions