Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function for cutting a string into sections without cutting words?

I'm trying to find a php function that will take a string and a length number, and at that length in the string will cut it, but not if its in the middle of a word, only if its a space, and will check for the nearest space to do so.

It also would continuously do this and return the array of strings with however long the original string was (IE if the original string was about 240 in length and I wanted to cut around 80, the array would be 3 strings large).

I found a couple of functions but none that does that, and I'm having trouble creating my own.

like image 307
VACIndustries Avatar asked Feb 04 '26 14:02

VACIndustries


2 Answers

The wordwrap function splits a string in lines of up to a given number of characters long.

It takes care of words and won't cut in the middle of a word (unless to tell it to).

You can use it and split the string by lines:

$string = wordwrap($string, 42);
$lines = explode("\n", $string);
like image 125
Arnaud Le Blanc Avatar answered Feb 07 '26 03:02

Arnaud Le Blanc


You want wordwrap().

wordwrap (string $str, int $width = 75, string $break = "\n" , bool $cut = false)

The important thing is to make sure you have $cut = false so it doesn't slice words into two parts (which is the default setting).

like image 45
Xeoncross Avatar answered Feb 07 '26 02:02

Xeoncross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!