Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut-off a string after the fourth line-break

Tags:

string

php

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.

like image 885
Frederick Behrends Avatar asked Dec 14 '11 10:12

Frederick Behrends


People also ask

How do you remove a line break in a string?

Remove All Line Breaks from a String We can remove all line breaks by using a regex to match all the line breaks by writing: str = str. replace(/(\r\n|\n|\r)/gm, ""); \r\n is the CRLF line break used by Windows.

Does string trim remove newline?

Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

How do I remove a line break in Notepad ++?

Remove line breaks QUICKLY with Notepad++. Just use ctrl+a and then ctrl+j and all your line breaks are removed!


1 Answers

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
}
like image 184
holographix Avatar answered Sep 30 '22 12:09

holographix