Clipping a line after a fourth line break

I have a problem: I want to disable the long line after the fourth line break and continue it 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 a line after the first \n , but I don't know how to do it after the fourth.

I hope you help me.

+4
source share
3 answers

you can blow the string and then take all the details 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 } 
+4
source
 echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring); 
+1
source

Something like that?

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

Source: https://habr.com/ru/post/1386291/


All Articles