Skip to content

Instantly share code, notes, and snippets.

@faisalman
Created April 18, 2011 08:06
Show Gist options
  • Save faisalman/924970 to your computer and use it in GitHub Desktop.
Save faisalman/924970 to your computer and use it in GitHub Desktop.
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
/**
* 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());
}
<?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;
}
?>
@AlLoud
Copy link

AlLoud commented Aug 9, 2018

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