goranseric
10/20/2015 - 8:07 PM

Regular Expression snippets to validate Google Analytics tracking code (in PHP, JavaScript)

Regular Expression snippets to validate Google Analytics tracking code (in PHP, JavaScript)

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
<?php
/**
 * Regular Expression snippet to validate Google Analytics tracking code
 * see http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty
 *
 * @author  Faisalman <movedpixel@gmail.com>
 * @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;
}
?>
/**
 * Regular Expression snippets to validate Google Analytics tracking code
 * see http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty
 *
 * @author  Faisalman <movedpixel@gmail.com>
 * @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());
}