如何在前 100 个字符之后添加<br />
?我的意思是只中断一次,而不是在每 100 个字符后添加<br />
。
$str="Apple has announced that co-founder, former CEO and chairman of the board Steve Jobs has passed away at the age of 56, so we take a look back at the famous innovator's life.At left, Steve Jobs, chairman of the board of Apple Computer, leans on the new 'Macintosh' personal computer following a shareholder's meeting Jan. 24, 1984, in Cupertino, Calif. The Macintosh was priced at $2,495.";
//echo substr($str, 0, 100).'<br />'; this will break sentence after 100 characters.
//echo wordwrap($str, 100, "'n<br />'n");this will add <br /> after each 100 characters.
我需要的是:
Apple has announced that co-founder, former CEO and chairman of the board Steve Jobs has passed away
<br /> <-- only add here.
at the age of 56, so we take a look back at the famous innovator's life.At left, Steve Jobs, chairman of the board of Apple Computer, leans on the new 'Macintosh' personal computer following a shareholder's meeting Jan. 24, 1984, in Cupertino, Calif. The Macintosh was priced at $2,495.
如果你的意思是写"100个字母后分手"而不是字符,那么substr
不行。wordwrap
确实会反复工作。因此,您需要手动查找 100 个字母并在那里注入中断:
$str = preg_replace('/^.{100,}?'b/s', "$0<br>", $str);
PHP 有一个函数,可以将一个字符串插入到另一个特定位置,它被称为 substr_replace
:
echo substr_replace($str, '<br>', 100, 0);
如果您需要支持 UTF-8(您没有指定任何编码(,您可以使用正则表达式和 preg_replace
来执行此操作,这也允许不剪切单词:
echo preg_replace('/^.{80,120}+'b/su', '$0<br>', $str);
您可以使用
substr
获取前 100 个字符并添加一个<br />
,然后在之后获取所有其他字符。例:
<?php
echo substr( $string , 0, 100)
, "<br />"
, substr( $string, 100 );
?>
$str="Apple has announced that co-founder, former CEO and chairman of the board Steve Jobs has passed away at the age of 56, so we take a look back at the famous innovator's life.At left, Steve Jobs, chairman of the board of Apple Computer, leans on the new 'Macintosh' personal computer following a shareholder's meeting Jan. 24, 1984, in Cupertino, Calif. The Macintosh was priced at $2,495.";
$first_part = substr ( $str ,0,100);
$second_part = substr ( $str ,100); //Goes to end of str
$new = $first_part."<br />".$second_part;
我会做这样的事情
<?
$str="Apple has announced that co-founder, former CEO and chairman of the board Steve Jobs has passed away at the age of 56, so we take a look back at the famous innovator's life.At left, Steve Jobs, chairman of the board of Apple Computer, leans on the new 'Macintosh' personal computer following a shareholder's meeting Jan. 24, 1984, in Cupertino, Calif. The Macintosh was priced at $2,495.";
for ($i = 0; $i < strlen($str); $i += 99)
{
if ((strlen($str) - $i) < 100) {
echo substr($str, $i, strlen($str));
} else {
echo substr($str, $i, 100);
}
echo "<br />";
}
?>
这可以工作:
$text = "...";
if (isset($text[100])) {
$text[100] = $text[100] . "<br />";
}