如何为正则表达式代码添加识别GTM跟踪ID的功能?
问题描述
我有一个用于爬取网页并检测网站上是否存在Google Analytics代码的PHP函数:
function checkUA($domain) { $input = file_get_contents($domain); if ( $input !== false ){ //regex to check for UA or GA4 code that returns all matches $regex = '/\b[A-Z][A-Z0-9]?-[A-Z0-9]{4,10}(?:\-[1-9]\d{0,3})?\b/'; //if there is a match, return a unique array (tracking may be included more than once) if(preg_match_all($regex, $input,$matches)){ return array_unique($matches[0]); }else{ //if no match is found, let us know return 'no match found'; } }else{ return 'Site is blocked from crawlers'; } }
该函数可识别以UA、YT、MO、G、DC、AW开头的跟踪ID,例如:UA-12345-1、G-J2DV45G等。
我尝试为上述正则表达式添加功能,使其同时检测Google Tag Manager(GTM)ID(如GTM-5TDMDSZ),但无法找到修改方法,特此求助。
解决方案
要兼容GTM格式的ID,只需调整正则表达式的开头部分——原正则仅支持1-2个大写字母开头的ID,而GTM是3个大写字母开头。修改后的正则可覆盖所有需要的ID格式:
$regex = '/\b(?:[A-Z]{3}|[A-Z][A-Z0-9]?)-[A-Z0-9]{4,10}(?:\-[1-9]\d{0,3})?\b/';
修改说明
(?:[A-Z]{3}|[A-Z][A-Z0-9]?):非捕获组,同时匹配两种开头规则[A-Z]{3}:匹配3个大写字母(对应GTM开头的ID)[A-Z][A-Z0-9]?:保留原有的1-2个字符开头的逻辑(对应UA、G、DC等GA系列ID)
- 其余部分保持不变,确保原有GA系列ID的匹配逻辑不受影响
完整修改后的函数
function checkUA($domain) { $input = file_get_contents($domain); if ( $input !== false ){ // 匹配GA系列ID和GTM ID的正则 $regex = '/\b(?:[A-Z]{3}|[A-Z][A-Z0-9]?)-[A-Z0-9]{4,10}(?:\-[1-9]\d{0,3})?\b/'; if(preg_match_all($regex, $input,$matches)){ return array_unique($matches[0]); }else{ return 'no match found'; } }else{ return 'Site is blocked from crawlers'; } }
修改后该函数可同时匹配:
- GA系列ID:UA-12345-1、G-J2DV45G、DC-67890、AW-123456等
- GTM ID:GTM-5TDMDSZ、GTM-ABC123等
内容的提问来源于stack exchange,提问作者Alex Douglas
相关产品推荐
相关产品推荐

