Reputation: 628
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
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
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
Reputation:
/^[a-zA-Z0-9\s\p{P}]+$/
Don't forget to mark the end of the string with $
Upvotes: 1