Last active
December 29, 2015 11:39
-
-
Save chasingmaxwell/7665297 to your computer and use it in GitHub Desktop.
Check that a string matches a pattern in PHP (similar to the html5 pattern attribute). Useful for fallback server-side validation of textfield inputs when the textfield is validated client-side with the html5 pattern attribute.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* HEADS UP! ---> turns out there is a better way to solve this problem. | |
* Use ^ and $ to signify the beginning and end in your regex pattern and | |
* then use preg_match(). It will get you the same result and faster! :) | |
*/ | |
/** | |
* Check that a string matches a pattern in PHP (similar to the html5 pattern | |
* attribute). | |
* | |
* @param string $string | |
* The string to check against the pattern. | |
* @param string $pattern | |
* A string containing a regular expression against which the string will be | |
* checked. For example, '/[a-zA-Z0-9]+/' is a whitelist pattern which only | |
* allows alphanumeric characters. | |
* @return | |
* TRUE if $string only contains characters which match the pattern, | |
* otherwise FALSE. | |
*/ | |
function string_matches_pattern($string, $pattern) { | |
$matches = array(); | |
preg_match($pattern, $string, $matches); | |
if (empty($matches) || (isset($matches[0]) && $matches[0] != $string)) { | |
return FALSE; | |
} | |
return TRUE; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, turns out this is entirely useless :). If you use ^ and $ to signify the beginning and end of your regex pattern then preg_match will give you the same result. so use preg_match!