Preg_match validating special chars inside a string

17,076

The problem is with the $ symbol. You are specifically asking it to match the end of string. The expression /[^a-z0-9 _]+$/i will not match hello"@£$joe because joe matches [a-z0-9 _]+$; so it obviously won't match when you negate the class. Remove the $ symbol and everything will be as expected:

if(preg_match('/[^a-z0-9 _]+/i', $name)) {
// preg_match will return true if it finds 
// a character *other than* a-z, 0-9, space and _
// *anywhere* inside the string
}

Test it in your browser by pasting these lines one by one in the JavaScript console:

/[^a-z0-9 _]+/i.test("@hello");        // true
/[^a-z0-9 _]+/i.test("joe@");          // true
/[^a-z0-9 _]+/i.test("hello\"@£$joe"); // true
/[^a-z0-9 _]+/i.test("hello joe");     // false
Share:
17,076
2by
Author by

2by

Updated on June 04, 2022

Comments

  • 2by
    2by almost 2 years

    I want to only allow letters, numbers, spaces, unserscore and hyphens.

    So far i thought that this preg_match would do the job:

    if(preg_match('/[^a-z0-9 _]+$/i', $name)) {
    $error = "Name may only contain letters, numbers, spaces, \"_\" and \"-\".";
    }
    

    But i just realized that special chars inside a string, would not generate an error. For example

    hello"@£$joe

    would not generate an error. Is it possible to make a little change and make it work, or do i need another solution?