简体   繁体   English

我该如何插入 <hr> 在第一个之后 <p> 要么 <br> 在某些文本的每5,000个字符之后?

[英]How can I insert a <hr> after the first <p> or <br> following every 5,000 characters of some text?

I have some very long passages. 我的段落很长。 I want to break them up for easier reading. 我想将它们分解以便于阅读。 I want to divide them by adding a <hr> tag for every 5,000 characters. 我想通过为每5,000个字符添加一个<hr>标签来对它们进行划分。 But I also don't want to divide the text in the middle of a paragraph. 但是我也不想在段落中间分割文本。 So I want to add the <hr> tag just after the first <p> or <br> of every 5,000 characters. 所以我想在每5,000个字符的第一个<p> or <br>之后添加<hr>标记。 The 'text' has HTML formatting already so we can find the <p> or <br> directly within the text. “文本”已经具有HTML格式,因此我们可以直接在文本内找到<p> or <br>

I can do it with PHP in the back end or JS/jQuery in the front-end, whichever is the better way. 我可以在后端使用PHP或在前端使用JS / jQuery,以更好的方式。

I'm a novice and I'm completely stuck. 我是新手,我完全被卡住了。 I don't know how to achieve this. 我不知道该如何实现。 Hope you can help. 希望能对您有所帮助。 Thank you very much! 非常感谢你!

Here is a solution in jQuery. 这是jQuery中的解决方案。 A jsFiddle is available. 可以使用jsFiddle

In the sample, I am splitting at 100 characters so we can see the effect. 在示例中,我将拆分为100个字符,以便可以看到效果。 The code is as follows: 代码如下:

$(function () {
    var counter = 0;
    $("p").each(function (i, element) {
        counter += $(element).text().length;
        if (counter > 100) {
            counter = 0;
            $(element).append("<hr/>");
        }
    });
});

The high level of the algorithm is to keep a counter of text sizes for each paragraph and when it exceeds the threshold, add a horizontal line and reset the counter. 该算法的高级功能是为每个段落保留一个文本大小的计数器,当其超过阈值时,添加一条水平线并重置该计数器。

Here is a solution in PHP 这是PHP中的解决方案

$text = "<p>bla...bla</p><p>bla...bla</p><p>bla...bla</p><p>bla...bla</p>"; 
$textArray = explode("</p>",$text);
foreach ($textArray as &$value) {
 echo $value."</p>";
 $countText = strlen(strip_tags($value))+$countText;
  if ($countText > 4999 )
   { echo "<hr/>"; $countText = ""; }
}

You probably want to explode it into sentences, then probably select a number maybe 5 sentences in every paragraph and then insert a <hr> after every 5 sentences. 您可能希望将其分解为句子,然后可能在每个段落中选择一个数字(可能是5个句子),然后在每5个句子之后插入一个<hr>

To explode text into sentences, you can look at php sentence boundaries detection 要将文本分解为句子,您可以查看php句子边界检测

  $(function () {
   var total_length = 0;
   $("p").each(function (i, element) 
   {
       total_length += $(element).text().length;
       if (total_length >= 5000) {
           total_length = 0;
           $(element).append("<hr/>");
        }
   });
 });

Hope it will work for you 希望它对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM