Search This Blog

Loading...

Thursday, December 8, 2011

Using SimpleHtmlDom, how to remove and replace a specific attribute

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();
http://stackoverflow.com/questions/4600928/using-simplehtmldom-how-to-remove-and-replace-a-specific-attribute

0 comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails