PaulSkinner
PaulSkinner

Reputation: 628

Regex to match punctuation and alpha numeric characters

I am trying to test a string to see if it contains characters other than alphanumeric or punctuation and, if it does, set an error. I have the code below, but it doesn't seem to work as it's letting "CZW205é" pass. I'm hopeless at regex and can't seem to resolve the problem.

if(!preg_match("/^[a-zA-Z0-9\s\p{P}]/", $product_id)) {
    $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
    continue;
}

Thanks in advance for your help.

Upvotes: 2

Views: 11248

Answers (3)

Oussama Jilal
Oussama Jilal

Reputation: 7739

That happens because you are only matching the first character, try this code :

if(preg_match("/[^\w\s\p{P}]/", $product_id)) {
    $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
    continue;
}

Note : \w is a shorthand for [a-zA-Z0-9_]

Upvotes: 1

stema
stema

Reputation: 92986

You can do

if(preg_match("/[^a-zA-Z0-9\s\p{P}]/", $product_id)) {
    $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes';
    continue;
}

[^...] is a negated character class, it will match as soon as it finds something that is not inside your class.

(And therefor I removed the negation before the preg_match())

Upvotes: 9

user657496
user657496

Reputation:

/^[a-zA-Z0-9\s\p{P}]+$/

Don't forget to mark the end of the string with $

Upvotes: 1

Related Questions