Jump to content

Cutting strings in parts


stijnvb

Recommended Posts

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?

Link to comment
Share on other sites

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++;
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.