如何在前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.
答案 0 :(得分:6)
如果你打算写“在字母之后分手”,而不是字符,那么substr
就不会这样做。并且wordwrap
确实可以正常工作。所以你需要手动找到100个字母并在那里注入一个休息点:
$str = preg_replace('/^.{100,}?\b/s', "$0<br>", $str);
答案 1 :(得分:5)
PHP具有在特定位置将字符串插入另一个字符串的功能,它被称为substr_replace
:
echo substr_replace($str, '<br>', 100, 0);
如果你需要支持UTF-8(你没有指定任何编码),你可以使用正则表达式和preg_replace
来执行此操作,这样也不会删除单词:
echo preg_replace('/^.{80,120}+\b/su', '$0<br>', $str);
答案 2 :(得分:3)
您可以使用substr
获取前100个字符并添加<br />
然后获取所有其他字符。例如:
<?php
echo substr( $string , 0, 100)
, "<br />"
, substr( $string, 100 );
?>
答案 3 :(得分:1)
$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;
答案 4 :(得分:0)
我会做这样的事情
<?
$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 />";
}
?>
答案 5 :(得分:0)
这可行:
$text = "...";
if (isset($text[100])) {
$text[100] = $text[100] . "<br />";
}