1

私は現在、phpを使用してこのHTML DOM PARSERを使用しています:http ://simplehtmldom.sourceforge.net/

選択した属性を削除して置き換える方法がわかりませんhref="style.css"。リンクをに置き換えたいのですが、"index/style.css"挿入するのは

索引/

または、HTMLコード全体から属性全体を置き換えますか?

4

3 に答える 3

12

これはそれを行う必要があります:

$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();
于 2011-01-05T11:07:18.653 に答える
1

公式マニュアルには、基本的に必要なものすべてをカバーするいくつかの例があります。

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

特定の手順で問題が発生した場合は、質問を更新して、コードの一部を提供してください。

于 2011-01-05T10:36:08.553 に答える
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
    }
于 2015-12-16T06:14:29.713 に答える