doushui3216 2011-03-06 11:21
浏览 48
已采纳

PHP:使用自定义信息查找并替换可点击(.php)链接

I want to be able to find and replace all clickable links in a piece of text with some custom information. Please consider the following example:

This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/help.php for more help. Visit http://www.mydomain.com/contact.php if you wish to contact us.

In the above text, I want to be able to replace all clickable ".php" links to something like below:

This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/mypage.php?url=help.php for more help. Visit http://www.mydomain.com/mypage.php?url=contact.php if you wish to contact us.

I tried using preg_replace and ereg_replace but it did not work for me.

All help is appreciated. Thank you.

  • 写回答

2条回答 默认 最新

  • dongqiang8683 2011-03-06 11:32
    关注

    It is only on your domain?

    $str = "This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/help.php for more help. Visit http://www.mydomain.com/contact.php if you wish to contact us.";
    
    $str2 = preg_replace('~(http://www.mydomain.com/)([^ ]+?)\.php~i', '\1mypage.php?url=\2.php', $str);
    
    // $str:
    // This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/mypage.php?url=help.php for more help. Visit http://www.mydomain.com/mypage.php?url=contact.php if you wish to contact us.
    

    (edit: corrected the output)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助