在图像正则表达式周围添加链接标记和rel =“lightbox”

时间:2015-04-24 20:51:45

标签: php html regex wordpress

当我得到<image>标签并且我想在它们周围添加链接标记以及rel lightbox属性时,如何更改此示例? 我想不出来。我对正则表达式一点都不好。

示例

$pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';

所以在我的情况下我有<img src="...." class="...." alt=".....">

我需要<a href="....." rel="lightbox" title="....."><img src="...." class="...." alt="....."></a> 我怎么改变这个? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

目前还不清楚你到底想做什么,但我会利用 DOM 代替这项工作。

$doc = DOMDocument::loadHTML('
     <img src="www.foo.com/1.gif" class="foo" alt="...">
     <img src="www.bar.com/1.jpg" class="bar" alt="...">
     <img src="example.com/2.jpg" class="example" alt="...">   
');

foreach ($doc->getElementsByTagName('img') as $node) {
   $link = $node->ownerDocument->createElement('a');

   $a = $node->parentNode->insertBefore($link, $node);

   $a->setAttribute('href', $node->getAttribute('src'));
   $a->setAttribute('rel', 'lightbox');
   $a->setAttribute('title', 'some title');

   $a->appendChild($node);
}

echo $doc->saveHTML();

<强>输出:

<a href="www.foo.com/1.gif" rel="lightbox" title="some title"><img src="www.foo.com/1.gif" class="foo" alt="..."></a>
<a href="www.bar.com/1.jpg" rel="lightbox" title="some title"><img src="www.bar.com/1.jpg" class="bar" alt="..."></a>
<a href="example.com/2.jpg" rel="lightbox" title="some title"><img src="example.com/2.jpg" class="example" alt="..."></a>