replace all “foo” between two HTML tags using REGEX (PHP code)

前端 未结 3 2013
暗喜
暗喜 2021-01-16 22:12

I want a regex code , to replace all \"foo\" strings to \"bar\" , between the html tags pre>< /pre>

here is an example :

< html>
< p>          


        
相关标签:
3条回答
  • 2021-01-16 22:53
    $string = '< html>
    < p> blah blah blah foo try foo< /p>
    < pre> foo try foo word foofoo < /pre>
    < /html>';
    $string = preg_replace('/foo(?=(?:.(?!< pre>))*< \/pre>)/Um', 'boo', $string);
    echo $string;
    
    0 讨论(0)
  • 2021-01-16 23:01

    You could use DOMDocument to extract the text content of your HTML tags, do a simple str_replace on the text and update the DOM.

    0 讨论(0)
  • 2021-01-16 23:16

    First, go get Simple HTML Dom

    // Create DOM from URL or file
    $html = file_get_html('http://www.google.com/');
    
    // Find the first pre (you can change this or find an array based on documentation on website to suit your needs, but I will make it just for the first pre for now
    $html->find('pre', 0)->plaintext = str_replace('foo', 'bar', $html->find('pre', 0)->plaintext);
    
    //Echo HTML
    echo $html;
    
    0 讨论(0)
提交回复
热议问题