在 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_replacing 完成),在这里:

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

以上将成功处理单引号和双引号,并且在输入的 imgsrc 之间是否有多个 space 也不会失败。