首页 > 语言 > PHP > 正文

PHP利用正则表达式将相对路径转成绝对路径的方法示例

2024-05-04 23:55:33
字体:
来源:转载
供稿:网友

前言

大家应该都有所体会,很多时候在做网络爬虫的时候特别需要将爬虫搜索到的超链接进行处理,统一都改成绝对路径的,所以本文就写了一个正则表达式来对搜索到的链接进行处理。下面话不多说,来看看详细的介绍吧。

通常我们可能会搜索到如下的链接:

<!-- 空超链接 --><a href=""></a> <!-- 空白符 --><a href=" " rel="external nofollow" > </a><!-- a标签含有其它属性 --><a href="index.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" $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)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对VeVb武林网的支持。


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选