【问题标题】:Make the path of an image absolute in PHP在 PHP 中使图像的路径成为绝对路径
【发布时间】:2015-04-09 00:57:36
【问题描述】:

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

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

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

【问题讨论】:

  • 作为替代方案,还可以选择以斜线开头的 url。像这样:&lt;img src="/images/myimage.png" /&gt;。如果您当前的路径是www.mysite.com/subpage/subsubpage.php,它将在www.mysite.com/images/myimage.png 中查找图像

标签: php string path


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    虽然您的应用肯定存在设计问题(此任务不能通过 preg_replacing 完成),但还是来吧:

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

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

    【讨论】:

    • 你说mustn't be done with preg_replacing然后你...使用preg_replace。
    • @Forien 感谢您向我解释我刚刚做了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2012-01-10
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多