PHP替换图像src并在包含不同html标签的字符串中添加图像标签中的新属性[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我有一个网站,我从数据库获取产品描述,并在PHP中解码这样的HTML,并在网页前端显示:

$data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');

它返回如下的html:

<div class="container">
 <div class="textleft">
  <p>
   <span style="font-size:medium">
    <strong>Product Name:</strong>
   </span>
   <br />
   <span style="font-size:14px">Some description here <a href="some-link">Click here to see full details.</a></span>
   </p>
 </div>
 <div class="imageblock">
  <a href="some-link">
   <img src="http://myproject.com/image/catalog/image1.jpg" style="width: 500px; height: 150px;" />
  </a>
 </div>
 <div style="clear:both">
</div>
<div class="container">
 <div class="textleft">
  <p>
   <span style="font-size:medium">
    <strong>Product Name:</strong>
   </span>
   <br />
   <span style="font-size:14px">Some description here <a href="some-link">Click here to see full details.</a></span>
   </p>
 </div>
 <div class="imageblock">
  <a href="some-link">
   <img src="http://myproject.com/image/catalog/image2.jpg" style="width: 500px; height: 150px;" />
  </a>
 </div>
 <div style="clear:both">
</div>

产品说明中可能有许多图像。我在我的例子中只添加了2个。我需要做的是用src="image/catalog/blank.gif"替换所有图像的每个图像的src并添加一个新属性

data-src="http://myproject.com/image/catalog/image1.jpg" 

对于图像1和

data-src="http://myproject.com/image/catalog/image2.jpg"

对于图像2. data-src属性应该获取每个图像的原始src值。我怎样才能做到这一点?我尝试过preg_replace,如下所示

$data['description'] = preg_replace('((\n)?src="\b.*?")', 'src="image/catalog/blank.gif', $data['description']);

它取代了每个图像的src属性,但是如何在原始图像路径中添加data-src。我在页面加载之前需要这个,所以有没有办法用PHP做到这一点?

php html regex preg-replace preg-match
2个回答
2
投票

只需调整正则表达式即可。使用(括号)捕获所需文本,然后使用$ 1或\ 1引用该组1。

preg_replace('(src="(.*?)")', 'src="image/catalog/blank.gif" data-src="$1"', $data['description']);

但是:Kua zxsw指出


1
投票

我想这可能就是你要找的东西:

https://repl.it/repls/SpottedZanyDiscussion

http://php.net/manual/en/domdocument.getelementsbytagname.php

我没有测试过这个,所以不要只是复制和粘贴。

© www.soinside.com 2019 - 2024. All rights reserved.