PHP Reg ex for parsing a link

和自甴很熟 提交于 2019-12-11 07:26:27

问题


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 :)


回答1:


Something like this i think:

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



回答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);


来源:https://stackoverflow.com/questions/4239425/php-reg-ex-for-parsing-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!