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

2025-05-27 0 90

前言

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62
<!-- 空超链接 -->

<a href=""></a>

<!-- 空白符 -->

<a href=" " rel="external nofollow" > </a>

<!-- a标签含有其它属性 -->

<a href="index.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" alt="超链接"> index.html </a>

<a href="/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" target="_blank"> / target="_blank" </a>

<a target="_blank" href="/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" alt="超链接" > target="_blank" / id=\"codetool\">

处理的第一步,设置成绝对路径:

?

1
http:// ... / ../ ../

然后本文讲讲如何去除绝对路径中的 './'、'../'、'/..'的实现代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
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)

总结

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP利用正则表达式将相对路径转成绝对路径的方法示例 https://www.kuaiidc.com/73634.html

相关文章

发表评论
暂无评论