doushi3715 2014-04-19 21:50
浏览 384
已采纳

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

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-19 22: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部