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

372 views Asked by At

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. 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. The 'text' has HTML formatting already so we can find the <p> or <br> directly within the text.

I can do it with PHP in the back end or JS/jQuery in the front-end, whichever is the better way.

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!

4

There are 4 answers

1
Kolban On BEST ANSWER

Here is a solution in jQuery. A jsFiddle is available.

In the sample, I am splitting at 100 characters so we can see the effect. 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.

0
limbenjamin On

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.

To explode text into sentences, you can look at php sentence boundaries detection

0
Tom On

Here is a solution in 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 = ""; }
}
0
Tristup On
  $(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