【问题标题】:Replacing link with plain text with php simple html dom用php simple html dom替换纯文本链接
【发布时间】:2013-09-25 00:35:08
【问题描述】:

我有一个程序可以从网络中删除某些页面;然后我想遍历剩余的页面并“取消链接”到那些已删除页面的任何链接。我正在使用 simplehtmldom。我的函数需要一个源页面 ($source) 和一个页面数组 ($skipList)。它找到链接,然后我想操纵 dom 将元素转换为 $link->innertext,但我不知道如何。有什么帮助吗?

function RemoveSpecificLinks($source, $skipList) {
    // $source is the html source file; 
    // $skipList is an array of link destinations (hrefs) that we want unlinked
$docHtml    = file_get_contents($source);
$htmlObj    = str_get_html($docHtml);
$links  = $htmlObj->find('a');
if (isset($links)) {
    foreach ($links as $link) {
        if (in_array($link->href, $skipList)) {
            $link->href = ''; // Should convert to simple text element
        }
    }
}
$docHtml    = $htmlObj->save(); 
$htmlObj->clear();
unset($htmlObj);
return($docHtml);
}

【问题讨论】:

    标签: php html simple-html-dom


    【解决方案1】:

    我从未使用过 simplehtmldom,但我认为这应该可以解决您的问题:

    function RemoveSpecificLinks($source, $skipList) {
        // $source is the HTML source file; 
        // $skipList is an array of link destinations (hrefs) that we want unlinked
    $docHtml    = file_get_contents($source);
    $htmlObj    = str_get_html($docHtml);
    $links  = $htmlObj->find('a');
    if (isset($links)) {
        foreach ($links as $link) {
            if (in_array($link->href, $skipList)) {
    
                $link->outertext = $link->plaintext; // THIS SHOULD WORK
    
                // IF THIS DOES NOT WORK TRY:
                // $link->outertext = $link->innertext;
            }
        }
    }
    $docHtml    = $htmlObj->save(); 
    $htmlObj->clear();
    unset($htmlObj);
    return($docHtml);
    }
    

    请给我一些反馈,看看这是否有效,并说明哪种方法有效,如果有的话。

    更新:也许你更喜欢这个:

    $link->outertext = $link->href;
    

    这样可以显示链接,但不能点击。

    【讨论】:

    • 谢谢!我选择了innertext,它保留了链接文本中的任何html格式,但纯文本、innertext或href都可以。如此明确的解决方案,我因为没有想到它而自责。再次感谢...
    • 没问题。很高兴我能帮忙:-)
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2014-08-01
    • 2013-08-15
    相关资源
    最近更新 更多