[英]Using SimpleHtmlDom, how to remove and replace a specific attribute
我目前正在使用使用php的HTML DOM PARSER: http : //simplehtmldom.sourceforge.net/
我对如何删除和替换所选属性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的本机DOM库 :
$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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.