开发者

Wrapping an img tag in an a tag with the src attribute as the href

I need help turning something like:

<img class="coup-pic" src="http://example.com/img/pic.jg" alt="" />

into:

<a href="http://example.com/img/pic.jg"><img class="coup-pic" src="http://example.com/img/pic.jg" alt="" /></a>

I need to be able to dynamically search for a string like the one above using PHP and wrap it in 开发者_JAVA百科an a tag with the src attribute used as the a tag. I think I'll need to use preg_replace, but I do not know the right regex to use.

Thanks for the help!


I'm not currently somewhere where I can test this, but give this a try:

$html = preg_replace('/(<img [^>]*src="([^"]*)"[^>]*>)/i', '<a href="$2">$1</a>', $html);


This appears to work:

preg_replace('/\<img class="([a-zA-Z0-9\-]*)" src="([A-Za-z0-9\-\.\:\/]*)" alt=""\/\>/','<a href="\\2"><img class="\\1" src="\\2" alt=""/></a>',$string);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜