Jensen
Jensen

Reputation: 11

PHP Reg ex for parsing a link

I've a PHP script that parse the POST content of a form (message) and transform any URL in a real HTML link. This is the 2 regular expressions I use:

$dbQueryList['sb_message'] = preg_replace("#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $dbQueryList['sb_message']);

$dbQueryList['sb_message'] = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $dbQueryList['sb_message']);

Ok it works well but now, in another script I would like to do the opposite. So in my $dbQueryList['sb_message'] I could have a link like this "<a href="http://google.com" target="_blank">Google</a>" and I would like to just have "http://google.com".

I cannot write the regex that can do that. Could you help me please? Thanks :)

Upvotes: 1

Views: 504

Answers (2)

It's safer to use DOMDocument instead of regex to parse HTML contents.

Try this code:

<?php

function extractAnchors($html)
{
    $dom = new DOMDocument();
    // loadHtml() needs mb_convert_encoding() to work well with UTF-8 encoding
    $dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));

    $xpath = new DOMXPath($dom);

    foreach ($xpath->query('//a') as $node)
    {
        if ($node->hasAttribute('href'))
        {
            $newNode = $dom->createDocumentFragment();
            $newNode->appendXML($node->getAttribute('href'));
            $node->parentNode->replaceChild($newNode, $node);
        }
    }

    // get only the body tag with its contents, then trim the body tag itself to get only the original content
    return mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
}

$html = 'Some text <a href="http://www.google.com">Google</a> some text <img src="http://dontextract.it" alt="alt"> some text.';
echo extractAnchors($html);

Upvotes: 1

shybovycha
shybovycha

Reputation: 12235

Something like this i think:

echo preg_replace('/<a href="([^"]*)([^<\/]*)<\/a>/i', "$1", 'moofoo <a href="http://google.com" target="_blank"> Google </a> helloworld');

Upvotes: 1

Related Questions