公司的网站主要是利用优化获取流量,工作的时间久了,慢慢的也在接触seo,利用自己的能力做一些小的工具去分析同行业网站的优化方案,其实也是在学习的过程。下面言归正传,直接上正则获取页面的tdk代码。
一、正则代码
preg_match("/<title>(.*)<\/title>/i", $html, $title);
preg_match("/<meta name=\"keywords\" content=(.*)\/>/i", $html, $keywords);
preg_match("/<meta name=\"description\" content=(.*)\/>/i", $html, $description);
二、PHP代码
/**
* 获取TDK
* @return string|\think\response\Json|\think\response\View
* @author 申霖
* @time 2019/7/30 0030 下午 8:01
*/
public function res()
{
$url = input('post.url');
if (!$url) {
return json(['code' => 100, 'msg' => '缺少url地址']);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($curl);
curl_close($curl);
if (!$html) {
return "未找到数据";
}
$data['title']['length'] = $data['keywords']['length'] = $data['description']['length'] = 0;
$data['title']['content'] = $data['keywords']['content'] = $data['description']['content'] = '';
$html = mb_substr($html, 0, 1000);
preg_match("/<title>(.*)<\/title>/i", $html, $title);
preg_match("/<meta name=\"keywords\" content=(.*)\/>/i", $html, $keywords);
preg_match("/<meta name=\"description\" content=(.*)\/>/i", $html, $description);
if (isset($title[1])) {
$data['title']['content'] = str_replace('"', '', $title[1]);
$data['title']['length'] = mb_strlen($data['title']['content']);
}
if (isset($keywords[1])) {
$data['keywords']['content'] = str_replace('"', '', $keywords[1]);
$data['keywords']['length'] = mb_strlen($data['keywords']['content']);
}
if (isset($description[1])) {
$data['description']['content'] = str_replace('"', '', $description[1]);
$data['description']['length'] = mb_strlen($data['description']['content']);
}
return view('tool/res', ['data' => $data, 'url' => $url]);
}