Home > other >  How replace text with DOMDocument
How replace text with DOMDocument

Time:05-20

Need change letter "a" to "1" and "e" to "2"

This is approximately html, in fact it is more nested

<body>
  <p>
    <span>sppan</span>
    <a href="#">link</a>
    some text
  </p>
  <p>
    another text
  </p>
</body>

expected output

<body>
  <p>
    <span>spp1n</span>
    <a href="#">link</a>
    some t2xt
  </p>
  <p>
    anoth2r t2xt
  </p>
</body>

CodePudding user response:

I believe your expected output has an error (given your conditions), but generally speaking, it can be done using xpath:

$html= '
[your html above]
';

$HTMLDoc = new DOMDocument();
$HTMLDoc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new DOMXPath($HTMLDoc);

# locate all the text elements in the html;:
$targets = $xpath->query('//*//text()');

#get the text from each element
foreach ($targets as $target) {
    $current = $target->nodeValue;

    #make the required changes
    $new = str_replace(["a", "e"],["1","2"], $current);
   
    #replace the old with the new
    $target->nodeValue=$new;
};
echo $HTMLDoc->saveHTML();

Output:

<body>
  <p>
    <span>spp1n</span>
    <a href="#">link</a>
    som2 t2xt
  </p>
  <p>
    1noth2r t2xt
  </p>
</body>
  • Related