PHP - How to replace a phrase with another?

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

How can i replace this

with this

easiest with PHP.



        
相关标签:
4条回答
  • 2020-12-21 12:20

    The reason not to parse HTML with regex is if you can't guarantee the format. If you already know the format of the string, you don't have to worry about having a complete parser.

    In your case, if you know that's the format, you can use str_replace

    str_replace('<p><span class="headline">', '<p class="headline"><span>', $data);

    0 讨论(0)
  • 2020-12-21 12:25

    dont parse html with regex! this class should provide what you need http://simplehtmldom.sourceforge.net/

    0 讨论(0)
  • 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 <h*> element instead of using the semantically superfluous "headline" class.

    0 讨论(0)
  • 2020-12-21 12:45

    Have you tried using str_replace?

    If the placement of the <p> and <span> tags are consistent, you can simply replace one for the other with

    str_replace("replacement", "part to replace", $string);
    
    0 讨论(0)
提交回复
热议问题