2

I am using php version 7.0.14. In spite of several good examples on stackoverflow, I cannot get my php regex to work. I've been trying for hours every conceivable combination. The problem comes in trying to allow periods and slashes, which must be escaped. I have tried enclosing the regex in double and single quotes. I have tried escaping with one backslash, two, three, four. It either errors out, lets everything through (like $) or does not allow periods and slashes.

    $strStreet = "123 1/2 S. Main St. Apt. 1";
   #$strRegEx = "/^[a-z0-9 ,#-'\/]{3,50}$/i";
    $strRegEx = '/^[a-z0-9 ,#-\'\/]{3,50}$/i';
    if (preg_match($strRegEx, $strStreet) === 0 ) {
     print "bad address";
    }

Thanks in advance for any help.

Xi Vix
  • 1,381
  • 6
  • 24
  • 43
  • thanks chris85 ... genius ... if you put your answer as an answer I can give you credit – Xi Vix Jun 24 '17 at 17:03
  • oops ... i just noticed the period is not escaped ... why is it not being interpreted as an "any character" – Xi Vix Jun 24 '17 at 17:05
  • Just an fyi, using addresses and regex together is not recommended https://smartystreets.com/articles/regular-expressions-for-street-addresses – camiblanch Jun 27 '17 at 22:25

1 Answers1

3

You have two issues here:

  1. there is no . in your character class (in a character class the . doesn't need to be escaped)
  2. the - in a character class needs to be escaped, or moved to the front or end (in other regex engines the escaping isn't available). On its own it creates a range of the characters on each side of it.

so:

^[-a-z0-9 ,#'\/.]{3,50}$

should work for you. (also if you use a different delimiter the forward slash won't need to be escaped)

Demo: https://regex101.com/r/PfZAlO/1/

chris85
  • 23,846
  • 7
  • 34
  • 51