Frederick Behrends
Frederick Behrends

Reputation: 3095

Cut-off a string after the fourth line-break

I've got the problem, that I want to cut-off a long string after the fourth line-break and have it continue with "..."

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

should become:

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

I know how to break the string after the first \n but I don't know how to do it after the fourth.

I hope you can help me.

Upvotes: 5

Views: 1761

Answers (3)

holographix
holographix

Reputation: 2557

you can explode the string and then take all the parts you need

$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
}

Upvotes: 4

akond
akond

Reputation: 16035

echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring);

Upvotes: 1

user898741
user898741

Reputation:

Something like this ?

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

Upvotes: 0

Related Questions