簡體   English   中英

在第四個換行符后切斷字符串

[英]Cut-off a string after the fourth line-break

我有問題,我想在第四個換行符后截斷一個長字符串,並讓它繼續“ ...”

<?php
$teststring = "asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa\n";
?>

應該變成:

<?php
$teststring = "asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa\n
               asddsadsadsadsaa...";
?>

我知道在第一個\\n之后如何斷開字符串,但在第四個之后我不知道如何執行。

我希望你能幫助我。

您可以將琴弦炸開,然后取出所需的所有零件

$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
}
echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring);

像這樣嗎?

$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>";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM