出品 | 漫云科技
整理 | 赵建平
<?php
// HTML字符串
$html = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title></title></head><body><script type='text/javascript'>location.href='https://www.baidu.com';</script></body></html>";
// 创建DOM解析器
$dom = new DOMDocument();
// 加载HTML
$dom->loadHTML($html);
// 查找script标签
$scripts = $dom->getElementsByTagName('script');
// 遍历所有script标签
foreach ($scripts as $script) {
// 获取script标签的文本内容
$scriptContent = $script->textContent;
// 使用正则表达式查找location.href的值
if (preg_match('/location\.href\s*=\s*["\'](.*?)["\'];/', $scriptContent, $matches)) {
$locationHrefValue = $matches[1];
echo "location.href的值是: $locationHrefValue";
}
}
?>
打印结果:
location.href的值是: https://www.baidu.com
再附加一个js的方法
// HTML字符串
var html = '<script>var location = {href: "https://www.example.com"};</script>';
// 使用正则表达式提取location.href的值
var regex = /location\.href\s*=\s*["'](.*?)["'];/;
var matches = html.match(regex);
if (matches && matches.length > 1) {
var locationHrefValue = matches[1];
console.log("location.href的值是: " + locationHrefValue);
} else {
console.log("未找到location.href的值。");
}