stijnvb Posted July 10, 2011 Share Posted July 10, 2011 Hi guys, I have long strings which I want to cut in smaller strings into an array. As an example, they should all be less than 2000 characters, and cut off to the dot (.) closest to the 2000th character. This way, a string of 10000 characters will likely be cut into 6 parts, all ending with a . What would be the best way to get this done? Quote Link to comment https://forums.phpfreaks.com/topic/241574-cutting-strings-in-parts/ Share on other sites More sharing options...
stijnvb Posted July 10, 2011 Author Share Posted July 10, 2011 Got home and put myself to it I got exactly what I needed, but I think this could be done so much shorter. Anyway, this might be useful for you: <?php // Split array into sentences (this removes the . after each sentence $tot_article_array = explode('. ', $tot_article); $current_add_period = 0; // Add the . after each sentence again while ($current_add_period < count ($tot_article_array)){ $tot_article_array[$current_add_period] .= "."; $current_add_period++; } $current_combine_count = 0; $trunk_array_count = 0; $trunk_array = array(); // Add sentences together to a string closest to 1000 characters while ($current_combine_count < count ($tot_article_array)){ if (strlen($trunk_array[$trunk_array_count]) + strlen($tot_article_array[$current_combine_count]) < "1000") { $trunk_array[$trunk_array_count] .= " " . $tot_article_array[$current_combine_count]; } else { $trunk_array_count++; } $current_combine_count++; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/241574-cutting-strings-in-parts/#findComment-1240906 Share on other sites More sharing options...
.josh Posted July 10, 2011 Share Posted July 10, 2011 $sentences = preg_split('~(.{1,998}\. )~s',$content,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); Quote Link to comment https://forums.phpfreaks.com/topic/241574-cutting-strings-in-parts/#findComment-1240919 Share on other sites More sharing options...
stijnvb Posted July 10, 2011 Author Share Posted July 10, 2011 Hi Crayon, Now that's what I call a solution! :-) That does exactly what I need!!! Thanks Quote Link to comment https://forums.phpfreaks.com/topic/241574-cutting-strings-in-parts/#findComment-1240922 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.