2011-01-05 41 views
1

我目前使用这个HTML DOM解析器使用PHP特定属性:http://simplehtmldom.sourceforge.net/使用SimpleHtmlDom,如何拆除和更换

我如何卸下并更换所选属性href="style.css"困惑,我想更换与"index/style.css"的链接,我应该仅插入

指数/

或更换从整个HTML代码全属性?

+0

为什么不使用本地PHP DOM解析器? – dqhendricks 2011-01-05 05:49:33

+0

你是什么意思原生PHP DOM PARSER? – woninana 2011-01-05 06:05:09

+1

@dqhendricks PHP DOM库提供了相当粗糙的功能集。您需要编写自己的许多基本功能。如果足够稳固,第三方库是一个不错的选择。 – 2011-01-05 10:34:50

回答

10

这应做到:

$doc = str_get_html($code); 
foreach ($doc->find('a[href]') as $a) { 
    $href = $a->href; 
    if (/* $href begins with a relative URL path */) { 
     $a->href = 'index/'.$href; 
    } 

} 
$code = (string) $doc; 

您还可以使用PHP’s native DOM library

$doc = new DOMDocument(); 
$doc->loadHTML($code); 
$xpath = new DOMXpath($doc); 
foreach ($xpath->query('//a[@href]') as $a) { 
    $href = $a->getAttribute('href'); 
    if (/* $href begins with a relative URL path */) { 
     $a->setAttribute('href', 'index/'.$href); 
    } 
} 
$code = $doc->saveHTML(); 
0
$html = str_get_html($string); 
if ($html){ // Verify connection, return False if could not load the resource 
    $e = $html->find("a"); 
    foreach ($e as $e_element){ 
     $old_href = $e_element->outertext; 
     // Do your modification in here 
     $e_element->href = affiliate($e_element->href); // for example I replace original link by the return of custom function named 'affiliate' 
     $e_element->href = ""; //remove href 
     $e_element->target .= "_blank"; // I added target _blank to open in new tab 
     // end modification 
     $html = str_replace($old_href, $e_element->outertext, $html); // Update the href 
    }