2010-11-21 60 views
1

我有一个PHP脚本,用于解析表单(消息)的POST内容,并在真正的HTML链接中转换任何URL。这是我使用的2个正则表达式:PHP Reg ex解析链接

$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']); 

好吧,它运作良好,但现在,在另一个脚本中,我想做相反的事情。所以在我的$dbQueryList['sb_message']我可以有这样的链接“<a href="http://google.com" target="_blank">Google</a>”,我想只有“http://google.com”。

我不能写出可以做到这一点的正则表达式。请问你能帮帮我吗? 谢谢:)

回答

1

事情是这样的,我认为:

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

它的安全使用DOMDocument代替正则表达式来解析HTML内容。

试试这个代码:

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