0

It seems to be working correctly, but if you put leading characters it doesn't check that and if you put ending characters it doesn't check that.

I want to make sure a string is in this format:

6 Numbers | Hyphen | 1 Number | A-Z any case | Hyphen | 5 Numbers

So like this 123456-1a-12345 and 123456-1A-12345 should work.

$string = 'this12345-1A-12345'; // This works, and it shouldn't
$string = '12345-1A-12345this'; // This also works and it shouldn't

$pattern = "([0-9]{6}[-]{1}[0-9]{1}[A-Za-z]{1}[-]{1}[0-9]{5})";
echo preg_match($pattern, $string);

What am I doing wrong? Sorry I am really new to preg_match, and I can't find any good libraries on syntax.

zzlalani
  • 22,960
  • 16
  • 44
  • 73
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Nov 21 '13 at 20:39

2 Answers2

3

You can use ^ to make the regex check for beginning of line and $ for the end of it.

$pattern = "(^[0-9]{6}[-]{1}[0-9]{1}[A-Za-z]{1}[-]{1}[0-9]{5}$)";

This pattern will only apply if the string has nothing before and after your specifications.

kero
  • 10,647
  • 5
  • 41
  • 51
3

You must only add anchors to mark the start and end of the pattern (and add pattern delimiters):

$pattern = "~^([0-9]{6}[-]{1}[0-9]{1}[A-Za-z]{1}[-]{1}[0-9]{5})$~";

As an aside, your pattern can be shorten to:

$pattern = '~^[0-9]{6}-[0-9][A-Z]-[0-9]{5}$~i';
preg_match($pattern, $string, $match);
print_r($match);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125