php - Regular expression to ensure all links have target="_blank" -
i have textarea uses ckeditor generate html. want ensure links user enters have target="_blank"
. thought i'd need 2 regex checks: 1 replace target="..."
target="_blank"
, , insert target attribute target attribute doesn't exist. i'm not making progress:
// target attribute doesn't exist, add preg_replace("/<a(\s*(?!target)([\w\-])+=([\\"\'])[^\\"\']+\3)*\s*\/?>/", "<a target="_blank"$1>", $input_lines);
this works in simple case:
<a href="#">one</a> ---> <a target="_blank" href="#">one</a>
it not work <a href="#" alt="hello">one</a>
, i'm not sure why don't things challenging regular expressions.
also, how replace existing target="..."
(e.g. target="_parent
") strictly target="_blank
"?
you can safely use php dom xpath set attributes or modify existing ones in <a>
tags this:
$html = <<<data <a href="somelink.html" target="_blank"><img src="myimage.jpg" alt="alt" title="sometitle" /></a> <a href="somelink1.php" target="_parent">link_no1</a> <a href="somelink2.php">link_no2</a> <a href="someimage.jpg"><img src="image2.png"></a> data; $dom = new domdocument('1.0', 'utf-8'); $dom->loadhtml($html, libxml_html_noimplied | libxml_html_nodefdtd); $xpath = new domxpath($dom); $links = $xpath->query('//a'); foreach($links $link) { $link->setattribute('target', '_blank'); } echo $dom->savehtml();
see ideone demo
output:
<a href="somelink.html" target="_blank"><img src="myimage.jpg" alt="alt" title="sometitle"><a href="somelink1.php" target="_blank">link_no1</a><a href="somelink2.php" target="_blank">link_no2</a><a href="someimage.jpg" target="_blank"><img src="image2.png"></a></a>
Comments
Post a Comment