Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

php - Using SimpleHtmlDom, how to remove and replace a specific attribute

I'm currently using this HTML DOM PARSER using php : http://simplehtmldom.sourceforge.net/

I'm confused on how to remove and replace the selected attribute href="style.css", I want to replace the link with "index/style.css", should I insert only the

index/

or replace the whole attribute from the whole html code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should do it:

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

You could also use 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...