3

This is not one of these "help me build my regex" questions. I have an HTML form input field where a user can provide geographical position data in various formats. The following regex works fine in regexr.com as well as in my application. However, I want to use the "pattern" parameter of HTML5 to additionally validate a user's input before submitting it.

((([E|W|N|S](\s)?)?([\-]?[0-1]?[(0-9)]{1,2})[°][ ]?([(0-5)]?[(0-9)]{1})([\.|,][0-9]{1,5})?['][ ]?([0-5]{0,1}[0-9]?(([\.|\,])[0-9]{0,3})?)([\"]|[']{2}){0,1}((\s)?[E|W|N|S])?)|([-]?[1]?[0-9]{1,2}[\.|,][0-9]{1,9}))

The point is that this regex contains a quote character ("). Now, I put this regex in my input like this:

<input type="text" pattern = "regex..."...." />

Browsers do not recognize this regex and don't do any validation at all, so obviously I need to escape that quote. What I tried so far:

  • PHP's addslashes() function escapes too many characters.
  • I escaped the quote with a single backslash

That did not change anything. I tested with Chrome, which works fine with simple regular expressions. The one above obviously is a bit too complicated.

I know the regular expression above is not perfect for matching coordinates, however, this is not to be discussed here. I just would like to know how to correctly escape a pattern in HTML5 as Chrome does not do anything with that regex.

1 Answer 1

10

Use HTML entities:

  • instead of ' use &apos;
  • instead of " use &quot;

If you're creating the regexp using PHP, you can use htmlentities() to encode a string using HTML entities. By default, this will just encode double quotes, but you can use the ENT_QUOTES option to encode both types of quotes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was the solution... even though I regularly use htmlentities() to display data, it did not occur to me that I could use it to encode my regex pattern... Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.