Menu

#67 Get only text in leaf nodes (avoid duplication)

Unassigned
open
nobody
None
2023-02-06
2023-02-06
olalav
No

Is there a way to search only for leaf nodes? It seems not, and this project has maybe gone stale :(

This is my workaround when wanting to find all texts in a node tree without getting duplicates.

Let me know if there is a better/official way to do this, or if support is added.

<?php
$string = "
<div>
  <foo>
    <bar>Span</bar>
    Foo
  </foo>
  <p>Hello</p>
  <p>World</p>
</div>
";

foreach(str_get_html($string)->find("div *") as $item) {
  $text = trim(preg_replace("~<([^>]*)>.*</\\1>~s", "", $item->innertext));
  printf("%s\n", $text);
}

?>

Discussion


Log in to post a comment.