I am trying to wrap a long text into 140 characters. This doesn't mean i don't need the text after 140 characters. I just need the text to be in chunks of 140 characters each. I first tried chunk_split but that was not up my expectations. Then i tried wordwrap() and that works. But my question though is i figured out how to add a custom "..." at the end of every wrapped string of 137 characters that counts up to 140 chars with "...". But how can i add custom suffix to every wrapped string? like "this is a string (1)", "this is a second string (2)" and so on instead of "..."? Basically i want numbers 1, 2, 3 etc. at the end of every wrapped string instead of the current "..." (dots). Here's my code:
<html>
<form name="longstring" action="longstring.php" method="POST">
<textarea rows="5" cols="100" name="typehere"></textarea>
<input type="submit" value ="submit">
</from>
<br/>
<?php
$longstring = $_POST["typehere"];
echo wordwrap($longstring,137,"...<br>") ;
?>
</html>
My idea:
<?php
$longstring = $_POST["typehere"];
$wrapped = wordwrap($longstring,137,"<br>");
$exploded = explode("<br>",$wrapped);
$i=1;
foreach($exploded as $x)
{
echo $x." (".$i++.") <br>";
}
?>
Output generated by wrapping 13 characters:
Lorem Ipsum (1)
is simply (2)
dummy text of (3)
the printing (4)
and (5)
typesetting (6)
industry. (7)
Lorem Ipsum (8)
has been the (9)
...
function lines($str, $len, $index = 0) {
$end = " ($index)
";
return (mb_strlen($str) < $len) ? ($str . $end) : mb_substr($str, 0, $len) . $end . lines(mb_substr($str, $len), $len, ++$index);
}
echo lines('abcdefghijklmnopqrstuv', 4);
the code above will output
abcd (0)
efgh (1)
ijkl (2)
mnop (3)
qrst (4)
uv (5)
$text = "1234567890123456789"; function stspl($str,$len,$index) { $htl=""; foreach(str_split($str,$len) as $splt) { $htl.=$splt."($index) "; $index++; } return $htl; } echo stspl($text,5,1); //here second parameter 5 is the length of chunk that you want... and third parameter is the index from where you want to start means(1) ,(2)
Ouput-
12345(1) 67890(2) 12345(3) 6789(4)
If you have many chuncks then you cannot use 137 anymore, after 9 chuncks you would result in a new chunk of 141 chars because of this:
137 + strlen("(") + strlen(")") + strlen("10") has a length of 141 chars.
This could help:
$longstring = "some long string";
$strlen = strlen($longstring);
$a=0;
$b=0;
$c=0;
while($c<$strlen){
$a++;
$b=138-strlen($a);
echo substr($longstring, $c, $b)."(".($a).")<br>";
$c+=$b;
}