你可以使用,
$str = 'src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"';
preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str);
哪个会返回,
src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"
贪婪/非贪婪
关于non-greedy 的评论意味着您可以使用(.*?) 而不是使用(.*)。你让它不贪婪的原因是因为(.*) 会尽可能多地匹配,例如,如果你的字符串包含两个图像链接:
$str = '<img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />';
然后,正则表达式中的(.*)会匹配从第一个“http://...”一直到第二个“/wp-content”的所有内容,
print_r(preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str));
^^
这将返回<img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />
使用非贪婪捕获会产生这个结果,
print_r(preg_replace("/(src=\")(.*?)(\/wp-content)/", "$1http://example.com$3", $str));
^^^
<img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />