CyberJunkie
CyberJunkie

Reputation: 22674

Regex for comma separated text

I create a text field for adding tags separated by commas. (e.g. php, jquery, js, ruby on rails) The field is like the one on stakoverflow where you add tags for posts.

I want to validate the input to ensure that tags have been entered correctly. This means that users may enter only letters, numbers, spaces, and commas.I made the following regex_match but I'm not entirely sure if it's correct.

regex_match[/^[a-z, ]+$/i]

If the input contains anything but what I added in the regex I get a validation error when I submit the form. I have tested and it works when I put symbols like ' " ; \

This is my first regex, am I doing it right? The language is PHP.

Upvotes: 0

Views: 5296

Answers (2)

Celmaun
Celmaun

Reputation: 24752

Why not use the str_getcsv function, It will parse the CSV string into an array and then you can validate each tag individually using the ctype_alnum function and discard the malformed ones ;)

Here is the correct regex pattern if you really need it:-

'/^[a-z0-9]+(, [a-z0-9]+)*$/i'

Upvotes: 3

Sylver
Sylver

Reputation: 8967

OK, there are a few problems here:

  1. There is no php function called "regex_match"
  2. a function uses (), not []
  3. variables start with $. The inside of [] is an index.

The line you posted will result in a syntax error in PHP. Since you "tested it", it means this is not really the code you used. Please post the actual code.

About the regex, it's a good first try, but you forgot the numbers:

/^[a-z,0-9 ]+$/i

Upvotes: 1

Related Questions