PHP:显示HTML的前500个字符

Vin*_*Vin 6 php dom domdocument

我在PHP变量中有一个巨大的HTML代码,如:

$html_code = '<div class="contianer" style="text-align:center;">The Sameple text.</div><br><span>Another sample text.</span>....';
Run Code Online (Sandbox Code Playgroud)

我想只显示此代码的前500个字符.此字符数必须考虑HTML标记中的文本,并在测量长度时排除HTMl标记和属性.但是在修改代码时,它不应该影响HTML代码的DOM结构.

是否有任何课程或工作范例?

Ale*_*x C 3

哦...我知道这一点,我无法完全理解它,但您想加载您作为 DOMDOCUMENT 获得的文本

http://www.php.net/manual/en/class.domdocument.php

然后从整个文档节点中获取文本(作为 DOMnode http://www.php.net/manual/en/class.domnode.php

这并不完全正确,但希望这能引导您走上正确的道路。尝试类似的方法:

 $html_code = '<div class="contianer" style="text-align:center;">The Sameple text.</div><br><span>Another sample text.</span>....';
 $dom = new DOMDocument();
 $dom->loadHTML($html_code);
 $text_to_strip = $dom->textContent;
 $stripped = mb_substr($text_to_strip,0,500);
 echo "$stripped";  // The Sameple text.Another sample text.....
Run Code Online (Sandbox Code Playgroud)

编辑好...应该可以。刚刚在本地测试过

编辑2

现在我知道您想保留标签,但限制文本,让我们看看。您需要循环播放内容,直到达到 500 个字符。这可能需要一些编辑和传递才能正确,但希望我能提供帮助。(抱歉我无法全神贯注)

第一种情况是文本少于 500 个字符。完全不用担心。从上面的代码开始,我们可以执行以下操作。

  if (strlen($stripped) > 500) {
       // this is where we do our work.

       $characters_so_far = 0;
       foreach ($dom->child_nodes as $ChildNode) {

          // should check if $ChildNode->hasChildNodes();
          // probably put some of this stuff into a function
          $characters_in_next_node += str_len($ChildNode->textcontent);
          if ($characters_so_far+$characters_in_next_node > 500) { 
              // remove the node 
              // try using 
              // $ChildNode->parentNode->removeChild($ChildNode);
          } 
          $characters_so_far += $characters_in_next_node
       }
       // 
       $final_out = $dom->saveHTML();
  } else {
        $final_out = $html_code;
  }
Run Code Online (Sandbox Code Playgroud)