Reputation: 95
i want replace all links in text With the exception of images Links
$text = '<p>
<a href="http://msn.com" rel="attachment wp-att-7046"><img class="alignnone size-full wp-image-7046" alt="geak-eye-mars" src="http://google/2013/06/geak-eye-mars.jpg" width="619" height="414" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>';
i want replace (http://msn.com and http://google.com)
and other links , but links of images like this (http://google/2013/06/geak-eye-mars.jpg)
Remain as it is ..
i hope u understand me .. i want only replace all links Between this tag
href="Link"
by this code
$text = ereg_replace("all links","another link">",$text);
Thank you
Upvotes: 1
Views: 209
Reputation: 95
$text = <<<LOD
<p><a href="http://msn.com" rel="attachment wp-att-7046">
<img src="http://google/2013/06/geak-eye-mars.jpg" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>
LOD;
$doc = new DOMDocument();
$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
@$doc->loadHTML($text);
$aNodes = $doc->getElementsByTagName("a");
foreach($aNodes as $aNode) {
$href = $aNode->getAttribute("href");
$new_href = '!!!Youhou!!! '. $href;
$aNode->setAttribute("href", $new_href);
}
$new_text = $doc->saveHTML();
Upvotes: 0
Reputation: 11945
If you want a permanent solution that won't break, use a DOM parser, like the other answers suggest. Using regular expressions to parse html is a really bad idea.
However, if you just want a one-time, quick solution, something like this will do:
preg_replace('/(href=["\']?)[^"\']+/', '$1' . $newtext, $html);
Guaranteed, this will fail on some html files (like if the URL is not wrapped in quotes), but it will work with most as long as the person who wrote the html file used best practices. Don't use this in production code. Ever.
Upvotes: 0
Reputation: 89649
Use the DOM to do this:
$text = <<<LOD
<p><a href="http://msn.com" rel="attachment wp-att-7046">
<img src="http://google/2013/06/geak-eye-mars.jpg" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>
LOD;
$doc = new DOMDocument();
@$doc->loadHTML($text);
$aNodes = $doc->getElementsByTagName("a");
foreach($aNodes as $aNode) {
$href = $aNode->getAttribute("href");
$new_href = '!!!Youhou!!! '. $href;
$aNode->setAttribute("href", $new_href);
}
$new_text = $doc->saveHTML();
Upvotes: 4