在網站流量分析與 SEO 優化中,了解訪客透過何種關鍵字從搜尋引擎進入網站至關重要。本文介紹一個實用的 PHP 類別,能自動偵測來路網址並解析出百度、Google、搜搜、搜狗等主流搜尋引擎的搜尋關鍵字。
Keyword 類別採用策略模式,根據 HTTP_REFERER 的網域自動選擇對應的解析方法:
wd=q=w=query=<?php
class Keyword {
public function getKeyword($referer) {
if (strpos($referer, "https://www.baidu.com") !== false) {
return $this->getBaiduKeyword($referer);
} elseif (strpos($referer, "https://www.google.com") !== false) {
return $this->getGoogleKeyword($referer);
} elseif (strpos($referer, "https://www.soso.com") !== false) {
return $this->getSosoKeyword($referer);
} elseif (strpos($referer, "https://www.sogou.com") !== false) {
return $this->getSogouKeyword($referer);
}
return '';
}
private function getBaiduKeyword($str) {
return $this->extractParam($str, 'wd=');
}
private function getGoogleKeyword($str) {
return $this->extractParam($str, '&q=');
}
private function getSosoKeyword($str) {
$kw = $this->extractParam($str, '?w=');
return $kw ?: $this->extractParam($str, '&w=');
}
private function getSogouKeyword($str) {
return $this->extractParam($str, 'query=');
}
private function extractParam($url, $param) {
$pos = strpos($url, $param);
if ($pos === false) return '';
$str = substr($url, $pos + strlen($param));
$end = strpos($str, '&');
if ($end !== false) $str = substr($str, 0, $end);
return rawurldecode($str);
}
}
?>
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$keyword = new Keyword();
$searchTerm = $keyword->getKeyword($referer);
if ($searchTerm) {
echo "訪客搜尋關鍵字:" . htmlspecialchars($searchTerm);
}
extractParam 方法,減少重複邏輯