PHP - How to replace a phrase with another?

前端 未结 4 607
半阙折子戏
半阙折子戏 2020-12-21 11:40

How can i replace this

with this

easiest with PHP.



        
4条回答
  •  时光取名叫无心
    2020-12-21 12:41

    Well, answer was accepted already, but anyway, here is how to do it with native DOM:

    $dom = new DOMDocument;
    $dom->loadHTMLFile("http://www.ihr-apotheker.de/cs1.html");
    $xPath = new DOMXpath($dom);
    
    // remove links but keep link text
    foreach($xPath->query('//a') as $link) {
        $link->parentNode->replaceChild(
            $dom->createTextNode($link->nodeValue), $link);
    }
    
    // switch classes    
    foreach($xPath->query('//p/span[@class="headline"]') as $node) {
        $node->removeAttribute('class');
        $node->parentNode->setAttribute('class', 'headline');
    }
    echo $dom->saveHTML();
    

    On a sidenote, HTML has elements for headings, so why not use a element instead of using the semantically superfluous "headline" class.

提交回复
热议问题