我有一个网站,我从数据库获取产品描述,并在 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 替换为 src="image/catalog/blank.gif"
为所有图像添加新属性
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 来做到这一点?
最佳答案
只需调整您的正则表达式即可。使用(括号)捕获所需的文本,然后使用 $1 或\1 引用该组 1。
preg_replace('(src="(.*?)")', 'src="image/catalog/blank.gif" data-src="$1"', $data['description']);
关于PHP替换图像src并从包含不同html标签的字符串在图像标签中添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55305310/