开发者

preg_replace add class to anchor tags ONLY between h1 tags

I need to add a custom class to every anchor tag found within h1 tags, leaving all other anchor tags untouched.

At the moment I have:

$content = preg_replace("/(<h1.*?<a.*?)/i","$1 class=\"mystyle\"",$content);

The problem with the above is that it only adds my class to the first anchor found in any h1 header and I'm really struggling to figure out how to correct this.

To clarify,

<h1><a href="page.html">Lorem</a> ipsum dolor sit <a href="page.html">amet</a>, consectetur adipiscing elit.</h1>
<h2><a href="page.html">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit.</h2>
<p><a href="page.html">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1><a href="page.html">Lorem</a> ipsum dolor sit <a href="page.html">am开发者_运维技巧et</a>, consectetur adipiscing elit.</h1>

Becomes,

<h1><a class="mystyle" href="page.html">Lorem</a> ipsum dolor sit <a href="page.html">amet</a>, consectetur adipiscing elit.</h1>
<h2><a href="page.html">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit.</h2>
<p><a href="page.html">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1><a class="mystyle" href="page.html">Lorem</a> ipsum dolor sit <a href="page.html">amet</a>, consectetur adipiscing elit.</h1>

Bit of a regex beginner so apologies if this is a really stupid question, I have searched for hours and hours trying to get this on my own so I hope someone can help! Cheers


Done with the help of $xpath->query('//h1//a');

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜