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

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

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历