PHP supports regular expressions through the use of the PCRE (Perl Compatible Regular Expressions) library which is enabled in almost all PHP installations. In PHP, you can use the
preg_match() function to test whether a regular expression matches a specific string. Note that this function stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Matching a String with Regular Expressions
We can write regular expressions for different use cases. Like we want to check if a string has only upper case alphabets or string has only fixed set of characters in it. There are many scenarios which can be easily validated with help of regular expressions. Here in this article we will try to focus on how to write different type of regular expressions with examples and explanations.
- Regular Expression / preg_match for matching a string against fixed set of characters.
If you have a fixed set of characters, against which you want to validate a string variable, you can use:
$result = preg_match("/[^ABC]/", $str);
Here, A, B, C is the fixed set of characters against which we are checking the $str variable. So, values like ABBA, BCA, CAB will pass this validation (0 means pass). And word with any other alphabet will not pass this preg_match (1 means fail).
- preg_match to check if a string has only alphabets.
Here, we are validating the string for only english alphabets (upper and lower case both).
- preg_match to check if a string has only alphanumerics.
Here, we are validating the string for alphanumeric characters only.
- preg_match to validate a url.
Here, we are validating the web URL and results in 0 is success, and 1 in case of failure.
- preg_match to validate a email.
preg_match will not work perfectly for email validation, but we often need to validate email. So, we can use "FILTER_VALIDATE_EMAIL".
This will validate any email.