我目前使用这个HTML DOM解析器使用PHP特定属性:http://simplehtmldom.sourceforge.net/使用SimpleHtmlDom,如何拆除和更换
我如何卸下并更换所选属性href="style.css"
困惑,我想更换与"index/style.css"
的链接,我应该仅插入
指数/
或更换从整个HTML代码全属性?
我目前使用这个HTML DOM解析器使用PHP特定属性:http://simplehtmldom.sourceforge.net/使用SimpleHtmlDom,如何拆除和更换
我如何卸下并更换所选属性href="style.css"
困惑,我想更换与"index/style.css"
的链接,我应该仅插入
指数/
或更换从整个HTML代码全属性?
这应做到:
$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();
官方手册中有几个例子,基本上涵盖了所有你需要:
http://simplehtmldom.sourceforge.net/manual.htm
如果你有一些具体的步骤的问题,请随时更新您的问题,并提供一些你的代码。
$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
}
为什么不使用本地PHP DOM解析器? – dqhendricks 2011-01-05 05:49:33
你是什么意思原生PHP DOM PARSER? – woninana 2011-01-05 06:05:09
@dqhendricks PHP DOM库提供了相当粗糙的功能集。您需要编写自己的许多基本功能。如果足够稳固,第三方库是一个不错的选择。 – 2011-01-05 10:34:50