Let's face it, regex is hard. So avoid using them whenever possible. Just to name a few cases where you should absolutely avoid them with a suitable alternative solution:
- Validating number ranges: use php comparison operators
- Validating email addresses: use
filter_var()
withFILTER_VALIDATE_EMAIL
and/or send an email already* - Validating IP addresses: use
filter_var()
withFILTER_VALIDATE_IP
- Validating URLs: use
filter_var()
withFILTER_VALIDATE_URL
* - Validating dates: see this Stack Overflow thread
- Parsing JSON: use
json_decode()
- Parsing HTML / XML: use a dedicated parser. See How do you parse and process HTML/XML in PHP?
- Parsing CSV: use
str_getcsv()
orfgetcsv()
- Parsing complex grammars: there's almost always a dedicated parser for your favourite language
- Check if string contains substring: use
strpos
orstripos
A few other cases you might consider avoiding:
- Name validation: read about Falsehoods Programmers Believe About Names
- Address validation: read about Falsehoods programmers believe about addresses
* It might not work with internationalized domains and email addresses. See top comments at the documentation.