在PHP中使图像的路径为绝对路径


Make the path of an image absolute in PHP

嗨,伙计们,我有一个$string,它包含了网站的所有文章,这里我有标签<img src="non absolute path" />,我需要添加http://hostname.com之前的路径,使其绝对。我试过这个,但不起作用

 $e["introtext"] = str_replace(
     "<img src='", 
     "<img src='http://hostname.com/",
     $e["introtext"]
 );

有什么建议吗?我想记住我需要替换字符串中的路径。感谢

您的代码似乎是对的,也许可以尝试添加其他引号:

 $e["introtext"]=str_replace('<img src="', '<img src="http://hostname.com/',$e["introtext"]);

虽然你的应用程序肯定有设计问题(这项任务不能用preg_replace完成),但现在开始吧:

$e["introtext"] = preg_replace(
     "#<img's+src=([''"])#", 
     "<img src='${1}http://hostname.com/",
     $e["introtext"]
 );

以上操作将成功处理单引号和双引号,并且无论输入中的imgsrc之间是否有多个空格,都不会失败。