【问题标题】:Using SimpleHtmlDom, how to remove and replace a specific attribute使用 SimpleHtmlDom,如何删除和替换特定属性
【发布时间】:2015-12-16 14:20:15
【问题描述】:

我目前正在使用这个 HTML DOM PARSER using php:http://simplehtmldom.sourceforge.net/

我对如何删除和替换所选属性href="style.css" 感到困惑,我想用"index/style.css" 替换链接,我应该只插入

索引/

还是从整个 html 代码中替换整个属性?

【问题讨论】:

  • 为什么不使用原生 PHP DOM 解析器?
  • 原生 PHP DOM PARSER 是什么意思?
  • @dqhendricks PHP DOM 库提供了相当粗略的功能集。您需要自己编写许多基本功能。如果第三方库足够可靠,它们是一个不错的选择。

标签: php parsing simple-html-dom


【解决方案1】:

应该这样做:

$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();

【讨论】:

    【解决方案2】:

    官方手册有几个例子,基本涵盖了你所需要的:

    http://simplehtmldom.sourceforge.net/manual.htm

    如果您对某些特定步骤有疑问,请随时更新您的问题并提供一些代码。

    【讨论】:

      【解决方案3】:
      $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
          }
      

      【讨论】:

        猜你喜欢
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多