简体   繁体   中英

replace all links in text by Regular Expressions

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

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();

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.

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM