So I understand that in latitude max 8 characters, 6 of which go after the point and the sign "-", and in longitude max 9 characters, 6 go after the point and the sign "-".

preg_match('/^\d{2}.\d{6}$/D', $_GET['latitude']) preg_match('/^\d{3}.\d{6}$/D', $_GET['longitude']) // 57.904683, -122.210420 

If so, how to correctly specify the optional minus in preg_match ?

    3 answers 3

    The optional minus is specified in a regular expression using a quantifier ? :

     ^-?\d{2}\.\d{6}$ 
    • ^ - beginning of line
    • -? - 1 or 0 minuses (quantifier ? Makes subtemplate optional)
    • \d{2} - 2 digits
    • \. - point (this sign must be escaped, because it is a special character that catches any character except newline characters)
    • \d{6} - 6 digits
    • $ - end of line (or \z , not to use /D )
    • What characters require shielding? In the description of the function preg_quote found: "the following characters are considered service preg_quote . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - " - are they? - Plush
    • It depends on whether these characters are inside a character class or not, and where in the character class they are. The separators should be shielded exactly. ? it necessary to escape outside character classes ? , + , * , | , ( , ) , [ , ^ , $ , \ ^ , as well as # and space (if the VERBOSE modifier is specified). It is advisable to screen { . Inside the character class you need to escape ] , - , ^ , \ . If the minus is at the beginning or at the end of the characters. class, do not screen it. If ] at the beginning is also not necessary. - Wiktor Stribiżew
    • (I hope it's not you who single-handedly voted for some of my answers (it seems four)? Otherwise these glasses will “burn out” tomorrow) - Wiktor Stribiżew

    Because The first digits can be in the range from 1 to 3, which is also necessary to indicate. {1,3} Negative -? 0 or 1

     preg_match('/^-?\d{1,2}\.\d{6}$/D', $_GET['latitude']) preg_match('/^-?\d{1,3}\.\d{6}$/D', $_GET['longitude']) 

      Try this:

       preg_match('/^[0-9]{2}\.[0-9]{6}$/D', $_GET['latitude']) preg_match('/^\-[0-9]{3}\.[0-9]{6}$/D', $_GET['longitude']) 
      • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky