I am validating the form input for a form field labeled 'tags', where users input tags that describe the uploaded image. After this validation, I preg_replace() any spaces with commas such that this input is csv input.
No matter the input, preg_match() returns 0. What am I doing wrong?
I want my tags to include:
- Begin with any letters (regardless of case) and/or numbers or space
- Contain any letters, numbers, spaces, commas, and hyphens
- End with any letters, numbers, spaces, or commas
Here is my regex string:
$regex = '/^[ ,][a-zA-Z0-9] (?:[ ,-] [a-zA-Z0-9])[ ,]$/';
This is my preg_match statement contained in an if statement where else exits the program (when preg_match returns 0).
preg_match($regex, $_POST['tags']) == 1;
Here are some example inputs and whether or not they should be valid.
- green-outline, triangle, 2d*% => invalid
- green-outline, triangle, 2d => valid
- green-outline triangle 2d => valid
I have tried the live regex tool at Regex101 but I can't figure out what's wrong.
CodePudding user response:
In that case I think something like this should work:
/^[\w, \-] $/g
NOTE: I removed the
\d
I had added previously since it's already included in\w
.
https://regex101.com/r/sfulPW/2
Edit
Here's how that regular expression works:
^
indicates the start of the line, that's where we should start matching.[\w, \-]
tells to match one or more\w
any word character or number (case insensitive),
any comma\-
any dash
$
indicates the end of the line, that's where we should stop matching.- The
g
flag allows us to make multiple matches.