0

I am fairly new to RegEx and felt I somewhat got the hang of the basics when I was working with my .htaccess file. I am currently working on some form validation to check that the user inputs a valid serial number to the system. The system can accept the following serial format.

  • I-SERIAL-123
  • I-SERIAL123
  • SERIAL-123
  • SERIAL123

I am using the preg_match function to check whether this expression is satisfied, if so the field is submitted.

Current Expression

if (preg_match("^[A-Z0-9\-]{5}$", $_GET['serial']) === false) 

However PHP keeps throwing an "No ending delimiter found" exception, I've looked at a couple of PHP cheat sheets and I don't see any immediate issues in my syntax.

Any pointers would be greatly appreciated, thanks.

Halfpint
  • 3,967
  • 9
  • 50
  • 92

1 Answers1

5

You need delimiters around your regex, usually /s:

if (preg_match("/^[A-Z0-9\-]{5}$/", $_GET['serial']) === false)
                ^---------------^

But any non-alphanumeric character is valid (even paired brackets), although it makes most sense to use ~, # or other symbols that aren't regex metacharacters or often used in text searches:

if (preg_match("#^[A-Z0-9\-]{5}$#", $_GET['serial']) === false)

In your case, as pointed out by Andy Lester, the regex engine thinks that ^ was supposed to be the delimiter (possible, but you then lose the "start of string" anchor for use in your regex and have to use \A instead):

if (preg_match("^\A[A-Z0-9\-]{5}$^", $_GET['serial']) === false)
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Ahhh I see, I feel so silly to think that it was only just that. I thought "/" represent that you are wanting to look for a trailing slash. Thanks very much sir. – Halfpint Sep 04 '13 at 14:10
  • 3
    To be more clear, PHP is seeing the `^` in the original query as the delimiter, and since the string doesn't end with a `^`, you get the "No ending delimiter found". – Andy Lester Sep 04 '13 at 14:10
  • Yes, the delimiter could be any non-alphanumeric symbol (such as `#` or `@`, for example) – Alma Do Sep 04 '13 at 14:11
  • [Regex cheatsheet](http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/) – DarkBee Sep 04 '13 at 14:42