PHP Simple Html Dom get the plain text of div,but avoiding all other tags

冷暖自知 提交于 2019-11-28 08:20:17

问题


I use PHP Simple Html Dom to get some html,now i have a html dom like follow code,i need fetch the plain text inner div,but avoiding the p tags and their content(only return 111111), who can help me?Thanks in advance!

<div>
    <p>00000000</p>
    111111
    <p>22222222</p>
</div>

回答1:


It depends on what you mean by "avoiding the p tags".

If you just want to remove the tags, then just running strip_tags() on it should work for what you want.

If you actually want to just return "11111" (ie. strip the tags and their contents) then this isn't a viable solution. For that, something like this may work:

$myDiv = $html->find('div'); // wherever your the div you're ending up with is
$children = $myDiv->children; // get an array of children
foreach ($children AS $child) {
    $child->outertext = ''; // This removes the element, but MAY NOT remove it from the original $myDiv
}
echo $myDiv->innertext;



回答2:


If you text is always at the same position , try this:

$html->find('text', 2)->plaintext; // should return 111111



回答3:


Here is my solution

I want to get the Primary Text part only.

 $title_obj = $article->find(".ofr-descptxt",0); //Store the Original Tree  ie) h3 tag
 $title_obj->children(0)->outertext = ""; //Unset <br/>
 $title_obj->children(1)->outertext = "";  //Unset the last Span
 echo $title_obj; //It has only first element

Edited: If you have PHP errors Try to enclose with If else or try my lazy code

   ($title_obj->children(0))?$title_obj->children(0)->outertext="":"";
   ($title_obj->children(1))?$title_obj->children(1)->outertext = "":"";

Official Documentation




回答4:


$wordlist = array("<p>", "</p>")

foreach($wordlist as $word)
     $string = str_replace($word, "", $string);


来源:https://stackoverflow.com/questions/25662569/php-simple-html-dom-get-the-plain-text-of-div-but-avoiding-all-other-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!