Created
April 18, 2011 08:06
-
-
Save faisalman/924970 to your computer and use it in GitHub Desktop.
Regular Expression snippets to validate Google Analytics tracking code (in PHP, JavaScript)
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
First, I don't get the exact pattern from google explanation at http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty so I just make some assumptions here (please correct if mistaken): | |
- general pattern must be: UA-xxxx-yy | |
- case-insensitive chars (so it could be 'ua', 'uA', whatever) | |
- x (account number) must be a number and could be in range of 4-9 digits | |
- y (profile within account) must be a number and could be in range of 1-4 digits |
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
/** | |
* Regular Expression snippets to validate Google Analytics tracking code | |
* see http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty | |
* | |
* @author Faisalman <[email protected]> | |
* @license http://www.opensource.org/licenses/mit-license.php | |
* @link http://gist.github.com/faisalman | |
* @param str string to be validated | |
* @return Boolean | |
*/ | |
function isAnalytics(str){ | |
return (/^ua-\d{4,9}-\d{1,4}$/i).test(str.toString()); | |
} |
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 | |
/** | |
* Regular Expression snippet to validate Google Analytics tracking code | |
* see http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty | |
* | |
* @author Faisalman <[email protected]> | |
* @license http://www.opensource.org/licenses/mit-license.php | |
* @link http://gist.github.com/faisalman | |
* @param $str string to be validated | |
* @return Boolean | |
*/ | |
function isAnalytics($str){ | |
return preg_match(/^ua-\d{4,9}-\d{1,4}$/i, strval($str)) ? true : false; | |
} | |
?> |
You can also simply cast the preg_match's result to a boolean instead:
return (bool) preg_match($code, strval($str));
You may also need to consider old tracking codes (e.g. UA-1234567
), therefore the last portion is optional:
return (bool) preg_match('/^ua-\d{4,10}(-\d{1,4})?$/i', $str);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one.
Although php needs quote around the regex: