我遇到了这个问题,我希望在第四次换行后切断一个长串并让它继续“......”
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n";
?>
应该成为:
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa...";
?>
我知道如何在第一个\n
之后打破字符串,但我不知道在第四个之后怎么做。
我希望你能帮助我。
答案 0 :(得分:4)
你可以爆炸字符串然后拿走你需要的所有部分
$newStr = ""; // initialise the string
$arr = explode("\n", $teststring);
if(count($arr) > 4) { // you've got more than 4 line breaks
$arr = array_splice($arr, 0, 4); // reduce the lines to four
foreach($arr as $line) { $newStr .= $line; } // store them all in a string
$newStr .= "...";
} else {
$newStr = $teststring; // there was less or equal to four rows so to us it'all ok
}
答案 1 :(得分:1)
echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring);
答案 2 :(得分:0)
这样的东西?
$teststring = "asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa";
$e = explode("\n", $teststring);
if (count($e) > 4)
{
$finalstring = "";
for ($i = 0; $i < 4; $i++)
{
$finalstring.= $e[$i];
}
}
else
{
$finalstring = $teststring;
}
echo "<pre>$finalstring</pre>";