[英]How to add unique suffix for wordwrap() in PHP?
我正在嘗試將一個長文本包裝成140個字符。 這並不意味着我不需要140個字符之后的文本。 我只需要每個140個字符的文本即可。 我首先嘗試了chunk_split,但這並沒有超出我的期望。 然后我嘗試了wordwrap(),並且有效。 但是我的問題是,我想出了如何在每個包含137個字符的包裝字符串的末尾添加自定義“ ...”的方法,該字符串最多包含140個字符,其中包含“ ...”。 但是,如何為每個包裝好的字符串添加自定義后綴? 例如“這是一個字符串(1)”,“這是第二個字符串(2)”等等,而不是“ ...”? 基本上我希望每個包裝的字符串的末尾都有數字1、2、3等,而不是當前的“ ...”(點)。 這是我的代碼:
<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>
function lines($str, $len, $index = 0) {
$end = " ($index)\n";
return (mb_strlen($str) < $len) ? ($str . $end) : mb_substr($str, 0, $len) . $end . lines(mb_substr($str, $len), $len, ++$index);
}
echo lines('abcdefghijklmnopqrstuv', 4);
上面的代碼將輸出
abcd (0)
efgh (1)
ijkl (2)
mnop (3)
qrst (4)
uv (5)
我的點子:
<?php
$longstring = $_POST["typehere"];
$wrapped = wordwrap($longstring,137,"<br>");
$exploded = explode("<br>",$wrapped);
$i=1;
foreach($exploded as $x)
{
echo $x." (".$i++.") <br>";
}
?>
通過包裝13個字符生成的輸出:
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)
...
$text = "1234567890123456789"; function stspl($str,$len,$index) { $htl=""; foreach(str_split($str,$len) as $splt) { $htl.=$splt."($index)\n"; $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)
如果您有很多塊,那么您將無法再使用137,在9個塊之后,由於以下原因,您將得到141個字符的新塊:
137 + strlen("(") + strlen(")") + strlen("10") has a length of 141 chars.
這可以幫助:
$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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.