Insert into array at random points

im trying to insert items into an array at random points…

I have a large paragraph of text which im trying to tidy up with some paragraph breaks at random points…

first im splitting the text into an array of sentences using the fullstop as a splitter

$sentences = explode(".", $text);

this gives me

$sentences[0] = text
$sentences[1] = text
$sentences[2] = text
$sentences[3] = text
$sentences[4] = text
$sentences[5] = text
$sentences[6] = text
$sentences[7] = text


what i would like to do is insert some new array items at random points so i end up with

$sentences[0] = text
$sentences[1] = text
$sentences[2] = </p></p>
$sentences[3] = text
$sentences[4] = text
$sentences[5] = text
$sentences[6] = </p><p>
$sentences[7] = text
$sentences[8] = </p><p>

I cant use shuffle because this would mess up the order of the sentences rendering the text unreadable

any ideas anyone please?

The simplest way to do this is just randomly insert your line breaks using the array_rand and [url=]array_splice functions:

function randomBreaks($sentences, $howmany) {
    $break = '.</p><p>';
    while ($howmany) {
        $howmany -= 1;
        $offset = array_rand($sentences);
        array_splice($sentences, $offset, 0, $break);
    return $sentences;

But the problem with that is that you might get line breaks next to each other, and you might get line breaks at the beginning and end, where they wouldn’t do any good. So the next simplest would be to add explicit checks for those situations (probably by looping through the complete “$sentences” array) in the “randomBreaks” function.

Easy, not pretty.

Edit: Now that I think about it, maybe there’s a better way. Instead of explicitly checking, you could just run the “randomBreaks” function as I wrote it, implode the array back into one long string, and then remove all the empty <p> elements, like so:

$sentences = explode('.', $text); // note that this will separate words like "Mr." as well
$howmany = /* decide how many breaks you want */;
$sentences = randomBreaks($sentences, $howmany);
$sentences = implode('', $sentences);
$sentences = str_replace('<p></p>', '', $sentences);

worked perfectly…

Thank you very much for your help i appreciate it :wink: