Sky
Sky

Reputation: 157

how to use preg_match_all to remove the <a> tag

$content = preg_replace("~(<a href=\"(.*)\">\w+)~iU", '', $content);
$ok = preg_replace("~(</a>)~iU", '', $content);
echo $ok;

I need to control the $content...

I want to remove all link in the $content....

even <a href="xx"><img xxxx> </a> all to remove A tag Just save <img xxx>...

How can I do?

I need edit the REGEX??

why I just can del the first one

Upvotes: 1

Views: 66

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

You can replace the anchors with their contents using DOMDocument:

$html = <<<'EOS'
<a href="xx"><img src="http://example.com"> </a>
<a href="xx"><img src="http://example.com"> </a>
EOS;

$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

foreach ($xpath->query('//a') as $anchor) {
    $fragment = $doc->createDocumentFragment();
    // collecting the child nodes
    foreach ($anchor->childNodes as $node) {
        $fragment->appendChild($node);
    }
    // replace anchor with all child nodes
    $anchor->parentNode->replaceChild($fragment, $anchor);
}

echo $doc->saveHTML();

Upvotes: 3

Related Questions