【问题标题】:Add image width and height in string在字符串中添加图像宽度和高度
【发布时间】:2014-04-15 14:33:04
【问题描述】:

我有一个这样的字符串:

<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;'></p>

这个字符串来自数据库,不幸的是,编辑器添加了这样的图像。

现在我想用 PHP 自动编辑这个:

<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;' height=100 width=30 align='right'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;' height=100 width=30 align='left'></p>

我想从样式中获取高度和宽度并将它们添加到 img 标签中。

这可能吗?

(这样我的图像将显示替代文本,而不是 Outlook 中的小方块。我希望它显示为完整图像)

【问题讨论】:

  • 嗯,为什么?目的是什么?
  • 样式上已经定义好了,不需要再添加属性了。
  • 用于时事通讯。当我使用样式时,它不会按应有的方式显示时事通讯,但是当我使用高度和宽度时,它会显示。
  • @prix 告诉 Outlook。当在样式中定义时,我的图像是一个小正方形,并且不显示替代文本。

标签: php html-parsing


【解决方案1】:

您可以使用preg_match_all 从样式中获取宽度和高度,然后使用 php str_replace 添加这些属性。匹配宽度高度的正则表达式如下所示:height:(.*?);width:(.*?);

$text = "<p>This is a paragraph with an image <img src='/url-to-img.jpg' style='height:100px;width:30px;float:right;'></p>
<p>This is another paragraph with an image <img src='/url-to-img.jpg' style='margin:10px;height:100px;width:30px;float:left;'></p>";

preg_match_all("/<img.*>/",$text,$out);
foreach($out as $t1)
{
    foreach($t1 as $img)
    {
        preg_match("/.*height:(.*?);width:(.*?);.*/",$img,$out2);
        $height = $out2[1];
        $width = $out2[2];
        $text = str_replace($out2[0],str_replace("<img","<img width='" . $width . "' height='" . $height . "'",$out2[0]),$text);
    }
}
echo $text;

【讨论】:

  • 谢谢!我能够从字符串中获取所有高度和宽度,但是如何将 preg_replace 函数应用于此?我实际上无法用新的高度或宽度替换当前的高度或宽度,因为它们仍在样式中。
猜你喜欢
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多