Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string after every five words

Tags:

php

preg-split

I want to split a string after every five words.

Example

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

Output

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

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

like image 668
Kamini Avatar asked Dec 20 '22 22:12

Kamini


2 Answers

You can use a regular expression too

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

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

like image 87
Galen Avatar answered Jan 03 '23 03:01

Galen


A simple algorithm would be to split the string on all spaces to produce an array of words. Then you could simply loop over the array and write a new line every 5th item. You really don't need anything fancier than that. Use str_split to get the array.

like image 37
Paul Sasik Avatar answered Jan 03 '23 02:01

Paul Sasik