Home > other >  Validating form input with preg_match() returns 0 every time
Validating form input with preg_match() returns 0 every time

Time:02-14

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:

  1. ^ indicates the start of the line, that's where we should start matching.
  2. [\w, \-] tells to match one or more of the following:
    • \w any word character or number (case insensitive)
    • , any comma
    • any space
    • \- any dash
  3. $ indicates the end of the line, that's where we should stop matching.
  4. The g flag allows us to make multiple matches.
  • Related