【问题标题】:Replace src attribute from img while keeping other attributes (like width and height)从 img 替换 src 属性,同时保留其他属性(如宽度和高度)
【发布时间】:2013-12-15 00:58:00
【问题描述】:

我有一个 html sn-p,里面有一张图片。我想替换 src 属性的值。 IE。从类似的东西获取:

<div style="position: relative" class="img-p"><a href="http://politiken.dk/indland/ECE2145750/nu-kommer-loven-om-alkolaase-spritbilister-skal-betale-6000-kr/"><img src="http://multimedia.pol.dk/archive/00802/RB_PLUS_Danskerne___802815p.jpg" width="369" height="253" alt="SPRITKONTROL" /></a></div>

到这样的事情:

<div style="position: relative" class="img-p"><a href="http://politiken.dk/indland/ECE2145750/nu-kommer-loven-om-alkolaase-spritbilister-skal-betale-6000-kr/"><img src="http://multimedia.pol.dk/archive/00802/SNOOTS.jpg" width="369" height="253" alt="SPRITKONTROL" /></a></div>

我试过了:

$content = preg_replace('/<img\s+src="([^"]+)"[^>]+>/i', '<img src="http://multimedia.pol.dk/archive/00802/SNOOTS.jpg"', $string); 
echo htmlspecialchars($content);

但这删除了宽度和高度以及 alt 属性。

【问题讨论】:

标签: php regex


【解决方案1】:

试一试:&lt;img\s+src=["']([^'"]+)["']

(替换为:&lt;img src="http://multimedia.pol.dk/archive/00802/SNOOTS.jpg"

转换这个:

&lt;img src="http://multimedia.pol.dk/archive/00802/RB_PLUS_Danskerne___802815p.jpg" width="369" height="253" alt="SPRITKONTROL" /&gt;

到这里:

&lt;img src="http://multimedia.pol.dk/archive/00802/SNOOTS.jpg" width="369" height="253" alt="SPRITKONTROL" /&gt;

这是一个工作示例:http://regex101.com/r/uE6oG5

【讨论】:

  • 我在你给我的链接上看到了你的工作示例......令人印象深刻......你能告诉我如何将正则表达式放入 PHP preg_replace 中吗?
  • 以他为例,只需将您的 preg_replace 更改为:preg_replace('/&lt;img\s+src=["']([^'"]+)["']/i', $source, $replace);
【解决方案2】:

好吧,不使用正则表达式逻辑,而是使用DOMDocument() 怎么样?这个例子对我有用:

# Source HTML for this example. Broken up into lines for readability.
$html_value = '<div style="position: relative" class="img-p">'
            . '<a href="http://politiken.dk/indland/ECE2145750/nu-kommer-loven-om-alkolaase-spritbilister-skal-betale-6000-kr/">'
            . '<img src="http://multimedia.pol.dk/archive/00802/RB_PLUS_Danskerne___802815p.jpg" width="369" height="253" alt="SPRITKONTROL" />'
            . '</a>'
            . '</div>'
            ;

# The new `img src` URL.
$new_img_src = 'http://multimedia.pol.dk/archive/00802/SNOOTS.jpg';

# Instantiate `DOMDocument()`
$dom = new DOMDocument();

# Laod the HTML into `DOMDocument()`
$dom->loadHTML($html_value);

# Parse the `img` tags.
$img_tags = $dom->getElementsByTagName('img');

# Roll through the `img` tags.
foreach ($img_tags as $tag) {

  # Set the `src` attribute to be the new value.
  $tag->setAttribute('src', $new_img_src);

  # Save the tag into the HTML.
  $dom->saveHTML($tag);
}

# Strip out the DOCTYPE, html & body tags.
$final_tags = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());

# Echo the final tags.
echo $final_tags;

【讨论】:

猜你喜欢
  • 2011-01-14
  • 2012-01-12
  • 2019-02-05
  • 2017-07-15
  • 2013-12-24
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多