Need regular expression to replace the part of image source
I want to replace below image source http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg
with http://www.test.com/test/uploads/2006/06/drop_off_area.jpg
Means I want to replace "http://www.fishingwithdon.com/wp-content/" with "http://www.test.com/test/"
But string I want to replace will not be same each time.
Any help will be appreciate开发者_运维技巧d.
Thanks,
Umesh Kulkarni
preg_replace ('/^(http:).*(\/)$/', 'http://www.test.com/test/', $src)
That should do the trick
$str = preg_replace(
'~\bhttp://www\.fishingwithdon\.com/wp-content/~',
'http://www.test.com/test/',
$str
);
http://codepad.org/xTvLGXC8
But wouldn't a simple str_replace be sufficient in your case?
$html = "<img src=\"http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg\"/>";
preg_match_all('#<img[^>]*>#i', $html, $match);
if(count($match) > 0)
{
foreach($match[0] as $image)
{
$new = preg_replace('/http:\/\/www\.(.+)\.com\//', 'http://www.test.com/test/', $image);
$html = str_replace($image, $new, $html);
}
}
echo $html;
Can Modify accordingly to adjust for different url situations ie (non-www, non-.com, https vs http)
Are you sure that you need a regex for that? Wouldn't str_replace be sufficient? It even says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
Example:
$replace_needle = 'http://www.fishingwithdon.com/wp-content/';
$replacement = 'http://www.test.com/test/';
$replace_haystack = 'http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg';
$result = str_replace($replace_needle, $replacement, $replace_haystack);
精彩评论