Split a line after every five words

I want to break a line after every five words.

Example

There is something to introduce here. This is a sample text.

Output

There is something to type
here. This is an example
text

How can this be done with preg_split()? Or is there a way to wrap text in PHP GD?

+3
source share
5 answers

You can also use regex

$str = 'There is something to type here. This is an example text';
echo preg_replace( '~((?:\S*?\s){5})~', "$1\n", $str );

You can print something here. This is a sample text.

+4
source

A simple algorithm would be to split the string across all spaces to create an array of words. Then you can just iterate over the array and write a new line every fifth element. You really don't need anything. Use str_split to get an array.

+3
source

, preg_spilt()

<?php
$string_to_split='There is something to type here. This is an example text';
$stringexploded=explode(" ",$string_to_split);
$string_five=array_chunk($stringexploded,5); 

for ($x=0;$x<count($string_five);$x++){
    echo implode(" ",$string_five[$x]);
    echo '<br />';
    }
?>
+2

PREG_SPLIT_DELIM_CAPTURE PREG_SPLIT_NO_EMPTY preg_split():

<?php
$string = preg_split("/([^\s]*\s+[^\s]*\s+[^\s]*\s+[^\s]*\s+[^\s]*)\s+/", $string, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

array (
  1 => 'There is something to type',
  2 => 'here. This is an example',
  3 => 'text',
)
+1
<?php 
function limit_words ($text, $max_words) {
    $split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    array_unshift($split,"");
    unset($split[0]);
    $truncated = '';
    $j=1;
    $k=0;
    $a=array();
    for ($i = 0; $i < count($split); $i += 2) {
       $truncated .= $split[$i].$split[$i+1];
        if($j % 5 == 0){
            $a[$k]= $truncated;
            $truncated='';
            $k++;
            $j=0;
        }
        $j++;
    }
    return($a);
}
$text="There is something to type here. This is an example text";

print_r(limit_words($text, 5));



Array
(
    [0] => There is something to type
    [1] =>  here. This is an example
)
0

All Articles