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

92vpleto  于 2023-10-22  发布在  PHP
关注(0)|答案(2)|浏览(98)

此问题已在此处有答案

How do you parse and process HTML/XML in PHP?(31个回答)
4年前关闭。
我有一个网站,我从数据库中获取产品描述,并像这样在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>

产品描述中可能有许多图像。在我的例子中,我只添加了两个。我需要做的是将所有图像的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来做吗?

olhwl3o2

olhwl3o21#

简单地调整你的正则表达式。使用(括号)捕获您想要的文本,然后使用$1或\1引用组1。

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

Demo:[Dead Link] https://repl.it/repls/SpottedZanyDiscussion

wrrgggsh

wrrgggsh2#

我想这可能是你正在寻找的:
http://php.net/manual/en/domdocument.getelementsbytagname.php

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

$doc = new DOMDocument();
$doc->loadHTML($data['description']);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
    $old_src = $tag->getAttribute('src');
    $new_src_url = 'image/catalog/blank.gif';
    $tag->setAttribute('src', $new_src_url);
    $tag->setAttribute('data-src', $old_src);
}
$data['description'] = $doc->saveHTML();

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

相关问题