2010-11-21 75 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);