I am not good at regex.
I got this string with some html <a>
tags and i need to strip some of them out, but only <a>
tags containing a certain value in the "href" attribut (mysite.com).
I still need to keep the link text, like the php function strip_tags($string, "<a>")
Here is what I got so far.:
/<a href=["\']?(http:\/\/mysite.com[^"\'\s>]+)["\'\s>]?/i
This is also working, but the problem is that I can't get the "text" in fx. <a href="http://mysite.com/testing/something">"text"</a>
So the input.:
Lorem ipsum <a href="http://mysite.com/testing/something">dolor</a> sit amet, <a href="http://keepingThisLink.com">consectetur</a> adipiscing elit. Duis dignissim <a href="http://mysite.com/testing">golor</a> vitae turpis fermentum tincidunt.
Should output.:
Lorem ipsum dolor sit amet, <a href="http://keepingThisLink.com">consectetur</a> adipiscing elit. Duis dignissim golor vitae turpis fermentum tincidunt.
Here's a more reliable, DOM-based approach:
<?php
$a = 'Lorem ipsum <a href="http://mysite.com/testing/something">dolor</a> sit amet, <a href="http://keepingThisLink.com">consectetur</a> adipiscing elit. Duis dignissim <a href="http://mysite.com/testing">golor</a> vitae turpis fermentum tincidunt.';
$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($a);
$domx = new DOMXPath($domd);
foreach ($domx->query("//a") as $link) {
$href = $link->getAttribute("href");
if ($href === "http://keepingThisLink.com") {
continue;
}
$text = $domd->createTextNode($link->nodeValue);
$link->parentNode->replaceChild($text, $link);
}
//unfortunately saveHTML adds doctype and a few unneccessary tags
var_dump(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $domd->saveHTML())));
the output is:
string(161) "
<p>Lorem ipsum dolor sit amet, <a href="http://keepingThisLink.com">consectetur</a> adipiscing elit. Duis dignissim golor vitae turpis fermentum tincidunt.</p>
"
You might want to look at PHP's DOM classes, they'll let you locate all the hyperlinks within a HTML document, get their href attributes and update/remove them in a way that's far more robust than attempting to do it with regex.
(Please note that the following example is "from the hip" and hasn't been tested)
$dom = new DOMDocument ();
// Load from a file
$dom -> load ('/path/to/my/file.html');
// Or load a HTML string
$dom -> loadHTML ($string);
// Or load an XHTML string as XML
$dom -> loadXML ($string);
// Find all the hyperlinks
if ($nodes = $dom -> getElementsByTagName ('a'))
{
foreach ($nodes as $node)
{
var_dump ($node -> getAttribute ('href'));
}
}