How to split a very long string at the first space before x characters?

If I have a variable with a very long string of text in it I need to split it into an array every 245 characters providing the 245th character is a space. If it isn’t I need to split it at the space closest to but before 245 characters. I need to repeat this until I get to the end of the very long string, if the last section is less than 245 characters that doesn’t matter.

I have Googled this and I can’t seem to find a solution that does exactly what i want to do.

Does anyone have any suggestions as to the best way to achieve exactly this requirement?

TIA

Colin

What have you tried so far?

I will try to get you started…

I think you will want to explode or preg_split your entire string into an array of words. From there you can build a new array and increment the index when the length is greater than 245.

I’m just going to go ahead and post my solution. I try to encourage people to try before asking for help but almost everything I’ve learned is from reading code.

Here you go:

[php]
$string = “Aliquam volutpat convallis libero in molestie. Donec eleifend est mollis tortor sollicitudin nec bibendum metus eleifend. Nullam tristique placerat nulla, ac ultricies lacus blandit vitae. Nullam pellentesque semper velit sit amet auctor. Curabitur quis erat et neque consectetur tincidunt. Suspendisse non turpis eu tortor consectetur molestie eget sit amet turpis. Vivamus ac tellus eget dolor hendrerit fermentum. Integer accumsan urna bibendum lacus fringilla facilisis. Phasellus arcu eros, ornare sit amet tristique ut, fermentum nec risus. Aenean lobortis molestie magna, ac lobortis tellus fermentum non. Pellentesque imperdiet, lacus ac cursus auctor, turpis ligula posuere nunc, pharetra placerat odio diam non diam. Aenean rhoncus sagittis lorem, non molestie nulla iaculis a. In pharetra purus in velit interdum vestibulum. Aliquam condimentum, mi ac varius convallis, tortor eros varius urna, non tristique eros nulla nec enim. Praesent vel nisl ut odio pretium varius. Phasellus eget mauris augue, viverra posuere ante. Nam ac nunc vitae neque pulvinar fringilla. Praesent at ante libero. Sed tincidunt mollis odio non lacinia. Praesent tincidunt lectus in libero interdum ullamcorper. Vivamus eleifend, enim a tristique vehicula, nunc diam feugiat nulla, non commodo velit quam sed nisl. Phasellus ullamcorper pharetra sapien, non cursus urna porttitor at. Pellentesque condimentum laoreet magna, vitae mollis nibh porttitor a. Vestibulum sit amet risus lorem, vel elementum nibh. Nulla suscipit eros sed magna posuere pharetra id aliquam massa. Sed at dui vel nisi blandit suscipit. Quisque lobortis volutpat mauris non facilisis. Nulla quis massa erat. Quisque vel magna dui, id volutpat leo. Donec sodales ipsum id orci gravida facilisis. Curabitur at turpis a ante feugiat luctus. Phasellus facilisis pharetra venenatis. Phasellus ultricies mattis nisl, et elementum libero varius ut. Sed blandit pharetra bibendum. Nam lobortis dignissim mi, id accumsan elit congue eu. Sed at dui mi. Aliquam congue malesuada metus non luctus. Mauris non tellus eu tellus rhoncus volutpat et pharetra ipsum. Nullam velit sapien, fermentum ac vestibulum eu, auctor non tellus. In placerat pulvinar enim sed rhoncus. Sed vulputate pharetra lorem sit amet tristique. Donec augue erat, sagittis ac aliquam a, ullamcorper at nisi. Morbi iaculis orci eget sem molestie at varius odio semper. Nunc magna justo, porta vel congue tincidunt, congue eget sapien. Morbi feugiat, odio eget sollicitudin pharetra, libero nisi blandit leo, ac vulputate turpis dolor malesuada erat. Proin sit amet nunc vitae metus porta varius eget tincidunt ipsum. Proin eu massa ut risus scelerisque scelerisque vel ac nibh.”;
$target_length = 245; // maximum string length

// split and loop words to create output array
$words = preg_split("/[\s]+/", $string); // split all words by spaces
$key = 0;
$output = array();

foreach($words as $word) {
$output[$key][] = $word; // append word to output array
$length = strlen(implode(" ", $output[$key])); // validate length of current output key

// if length is greater than target length move (pop & shift)
// the last word from the current key to the next key
if ($length > $target_length) {
	$pop = array_pop($output[$key]); // pop the last word
	$key++; // increment the key
	$output[$key][] = $pop; // shift last word to new key
}

}

// implode back to strings
foreach($output as $key => $value) {
$output[$key] = implode(" ", $value);
}

// test the length of each string
echo “

”;
echo “KEY\tLENGTH\tSTATUS\n”;
foreach($output as $key => $value) {
$length = strlen($value);
echo $key . “\t” . $length . “\t” . ($length > $target_length ? “TOO BIG” : “OK”) . “\n”;
}
echo “
”;
[/php]

Example output:

KEY	LENGTH	STATUS
0	238	OK
1	245	OK
2	241	OK
3	239	OK
4	240	OK
5	245	OK
6	241	OK
7	242	OK
8	243	OK
9	241	OK
10	236	OK
11	36	OK

Matt

Thank you very much for coding this for me it was not what I expected. :o

I was looking for a high level view of the best way to do it and was going to code it myself. I had been through Stack Exchange and got totally confused over the best way to do this as there are about 20 threads doing something similar. Even the individual answers on each thread were disagreeing with each other on the way to do it.

I was expecting a reply along the lines of (using your code as the example) use preg split to split the sentence into words then concatenate into sentences not what you did for me.

I will give your code a try thank you once again :slight_smile:

Matt

Thanks very much it worked perfectly, there were no functional changes to make to your code. It certainly saved me a couple of hours coding. :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service