It’s probable that during your life as PHP developer, you have used regular expressions on numerous occasions to validate well-formatted IP and email addresses, phone numbers, alphabetic data, and so forth, so I will assume that you’re familiar with its most basic aspects. The filter extension provides another filter called FILTER_VALIDATE_REGEXP, which permits you to determine if the value stored in a variable matches a specified regular expression pattern. To demonstrate more clearly how this filter does its thing, below I included a new code sample that simply checks if a given string begins with the uppercase A character. Here it is: // example on working with basic regular expressions
$value = 'Alejandro Gervasio'; if(filter_var($value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^A(.+)/"))) === FALSE) // displays Match was found. { echo 'No match was found.'; } else { echo 'Match was found.'; } Here you have it. As shown above, the FILTER_VALIDATE_REGEXP filter comes in extremely handy for validating values according to a specific regular expression. Of course, in this particular case, I decided to keep the sample regular expression very simple, to help you grasp more quickly how this filter works; naturally, more complex expressions can be used to suit different requirements. Below there’s a similar example that uses the FILTER_VALIDATE_REGEXP filter, but this time for determining if the string being evaluated starts with the “G” letter. Look at it, please: // example on working with basic regular expressions
$value = 'Alejandro Gervasio'; if(filter_var($value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^G(.+)/"))) === FALSE) // displays No match was found. { echo 'No match was found'; } else { echo 'Match was found.'; } Definitely, understanding the logic that drives the previous example is a pretty straightforward process that can be tackled with minor hassles. Again, it’s valid to note how the regular expression is passed to the “filter_var()” function as an additional argument, which we already saw in the preceding code sample. Well, at this stage I provided you with a quick overview of how to use the FILTER_VALIDATE_REGEXP filter to determine if the value assigned to a variable matches a given regular expression pattern. Next I will explain how to utilize the functionality of the filter extension for validating URLs. As you might have guessed, this new task will be performed by way of yet another filter. Thus, to learn more about it, click on the link that appears below and read the next section.
blog comments powered by Disqus |
|
|
|
|
|
|
|