前言背景与需求分析
前言
在进行网络爬虫开发时,经常需要将抓取的超链接进行标准化处理,即把所有相对链接统一转换为绝对路径。为此,这里提供一段基于正则表达式的PHP代码来实现这一功能。接下来将详细展开具体步骤。
常见相对链接格式解析
通常情况下,从网页中提取到的链接可能呈现多种相对形式,例如当前目录下的文件、上级目录的文件或根目录下的文件等。
index.html
/ target="_blank"
target="_blank" / alt="超链接"
target="_blank" title="超链接" / alt="超链接"
/
a
/index.html?id=1
?id=2
//index.html
//www.mafutian.net
http://www.hole_1.com/index.html
http://www.mafutian.net
http://www.numberer.net
1.jpg
1.jpeg
1.gif
1.png
1.txt
index.html
index.html
./index.html
../index.html
.../
...
javascript:void(0)
a:b
/a#a:b
mailto:'mafutian@126.com'
/tencent://message/?uin=335134463
.
..
../
/a/b/..
/a
./b
./././././././././b
../c
../../d
../a/../b/c/../d
./../e
http://www.hole_1.org/./../e
./.././f
http://www.hole_1.org/../a/.../../b/c/../d/..
:8081/index.html
:80/index.html
http://www.mafutian.net:8081/index.html
http://www.mafutian.net:8082/index.html
相对路径转绝对路径策略
首先,我们需要将这些相对路径解析为完整的绝对路径格式,以便后续的统一管理和访问。
http:// ... / ../ ../
清理路径中的冗余符号
接着,重点讲解如何通过代码逻辑去除绝对路径中残留的 './' 和 '../' 等冗余符号,从而得到规范化的URL字符串。
function url_to_absolute($relative)
{
$absolute = '';
// 去除所有的 './'
$absolute = preg_replace('/(?<!\.)\.\//','',$relative);
$count = preg_match_all('/(?<!\/)\/([^\/]{1,}?)\/\.\.\//',$absolute,$res);
// 迭代去除所有的 '/abc/../'
do
{
$absolute = preg_replace('/(?<!\/)\/([^\/]{1,}?)\/\.\.\//','/',$absolute);
$count = preg_match_all('/(?<!\/)\/([^\/]{1,}?)\/\.\.\//',$absolute,$res);
}while($count >= 1);
// 除去最后的 '/..'
$absolute = preg_replace('/(?<!\/)\/([^\/]{1,}?)\/\.\.$/','/',$absolute);
$absolute = preg_replace('/\/\.\.$/','',$absolute);
// 除去存在的 '../'
$absolute = preg_replace('/(?<!\.)\.\.\//','',$absolute);
return $absolute;
}
$relative = 'http://www.mytest.org/../a/.../../b/c/../d/..';
var_dump(url_to_absolute($relative));
// 输出:string 'http://www.mytest.org/a/b/' (length=26)
文章总结与交流互动
总结
上述内容展示了利用正则表达式在PHP中转换相对路径的核心思路与实现方法。希望这些技巧能对您的编程工作或学习有所帮助。如有任何疑问,欢迎留言讨论,感谢支持。