I have to insert a <br> tag after every 52 words so that it displays a line break otherwise the paragraph keeps going on and on increasing its width rather that the height. If there is any other, better way, please tell me.
My code
<?php
$str = "Hello world. My name is Yash Mathur and I am a student.
I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com
to seek for an answer. Please help me insert a line break after every 52 characters.
Thanks in advance!";
$len = strlen($str);
if ($len > 52) {
$str = substr($str, 0, 52) . "<br>";
}
echo $str;
?>
I need to somehow put this in a loop to insert the <br> tag every 52 characters.
I assume what you are trying to achieve in the end, is just a decent-looking paragraph, whose line-length is not too long, as to become hard to read. I believe this is a cosmetic issue, that can be better addressed in the presentation layer of your application, i.e. the style sheet.
In the style belonging to the paragraph, you could just add a “width:250px” (250px is an arbitrary value) to constrain the text into a self-wrapping box that is defined by the width of the paragraph.
I would not do it in PHP unless there is a really valid reason for this, because, if you ever need to change the look of your paragraph, you would then have to delve into your PHP code. This might seem trivial now, but in a couple months you probably will not even remember writing such code in the first place. This will lead to a minor headache at best, and a great deal of wasted time searching for just this formatting function.
Please rethink your strategy.