doushi3715 2014-04-20 05:50
浏览 381
已采纳

正则表达式匹配一个网址并替换为另一个网址

Helo,

I am a regular expression noob, trying to find resources online but the language is so foreign to me. Appreciate if anyone can help to shed some light on this.

Basically, I have successfully able to use dom method to find an image url in "img" tag using getAttribute('src') in a random string.

Example:

$string = '<a><img src=http://123.com/123.jpg/></a><img src=http://test.com/test.jpg/>'; //some random string
$url = get_img_url($string) //function of getting a url from a string.

Now here comes the challenge. How do I replace $url with another url, say, $url2? And subsequently save to $newstring? I have thought of using preg_replace, but how do I go about having this?

$url2 = 'http://example.com/content_image/blogger_1.jpg';
$find = ???                 //find $url i gotten in the function above in $string
$replace = ???              //replace with $url2
$newstring = preg_replace($find, $replace, $string);

Any help would be appreciated! Thanks guys!

Edited: Appended desired output, thanks Amit Joki!

echo $newstring;

Result would be:

<a><img src=http://example.com/content_image/blogger_1.jpg/></a><img src=http://test.com/test.jpg/>
  • 写回答

2条回答 默认 最新

  • duanjiao6730 2014-04-20 06:00
    关注

    You can use this regex:

    (<img.+?src=)(.+?)(\s|>)
    

    and replace it with:

    $1http://example.com$3
    

    Demo

    I don't know php, but you've to do it as:

    preg_replace($pattern, $replacement, $string);
    

    where $pattern is my regex, $replacement is my replace string and $string is your inputstring.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度