dongzhan1948 2015-03-21 14:02
浏览 44
已采纳

PHP:用绝对域URL替换相对顶部URL“../”

I want to convert relative URLs that starts with ../stuff/more.php to http://www.example.com/stuff/more.php in my RSS feed.

I used this PHP code to do so is the following:

$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$2$3', $content);

The result is wrong thought, it returns the URL like this

http://www.example.com/../stuff/more.php

Notice the ../ part hasn't been removed, please help!

So Basically..

This what I have: ../stuff/more.php

This is what I get (after running the code above): http://www.example.com/../stuff/more.php

This what I WANT: http://www.example.com/stuff/more.php

  • 写回答

5条回答 默认 最新

  • douceng7070 2015-03-21 15:01
    关注

    Adding (\.|\.\.|\/)* should work.

    $content = preg_replace("#(<\s*a\s+[^>]href\s=\s*[\"'])(?!http)(../|../|/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);

    Also, note $2$3 has been changed to $3$4

    Edit:

    Reduced to one alternative:

        $content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)(\.\.\/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 安卓13,动态广播无法接受
  • ¥50 docker运行容器端口如何映射(不重启服务、不重建容器)
  • ¥50 基于TwinCAT3实现力传感器的实时读取
  • ¥20 python求解八元一次不定方程,无数解中随机输出几组即可(相关搜索:用python)
  • ¥50 libreoffice导出PPTX到PDF中的错误换行问题
  • ¥15 python实现网页视频下载
  • ¥15 如何通过深度图获得物体的完整、正确点云?
  • ¥15 有没有操作系统适用白丁的经典的书籍,如何解决?(标签-学习)
  • ¥15 Catia V5 R20 64位 安装过程中选择orbix配置创建套接字失败
  • ¥100 C51单片机设计交通灯时出现的问题