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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With