user2606353
user2606353

Reputation: 79

Find all occurrences of a space preceded by a dot, then randomly replace theses spaces with newlines

This is my function:

$words = explode('. ', $desc);
$out = '';
foreach ($words as $key => $value) {
    $out .= $value;
    $rand = rand(0, 4);
    if ($rand == 2) {
        $out .= "\n";
    } else {
        $out .= ' ';
    }
}

In short, it's inserting new lines after random dots, but in this case dots are removed.

How could I do explode('. ', $desc), and leave dots in where they are?

Upvotes: 2

Views: 114

Answers (4)

mickmackusa
mickmackusa

Reputation: 47992

You don't need to explode your string and loop over the array. This can all be done with a single call of preg_replace_callback().

To randomly replace newlines with spaces which follow a dot, just match a dot, forget that you matched the dot with \K, then conditionally replace that space with a newline with preconfigured randomness. Demo

$text = 'Here. Is. A. Test. String. Apply. Random. Newlines.';

echo preg_replace_callback(
         '/\.\K /',
         fn() => rand(0, 4) === 2 ? "\n" : ' ',
         $text
     );

Potential output:

Here. Is.
A. Test. String. Apply. Random.
Newlines.

Upvotes: 0

Prashant Parekh
Prashant Parekh

Reputation: 428

Try this code..

$words = explode('. ',$desc);

            $out = '';
            foreach ($words as $key => $value) {

                $out .= $value;
                $rand = rand(0, 4);
                if ($rand == 2) {
                   $out .= "<br>";
                } else {
                   $out .= ' ';
                }
            }

Upvotes: 0

Flosculus
Flosculus

Reputation: 6956

Positive look behind without regex subject.

$words = preg_split('/(?<=\.)(?!\s*$)/', $desc);

Split at any non-character with a dot behind it.

Upvotes: 0

Tigger
Tigger

Reputation: 9130

Just put them back in when you concatenate.

$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
    $out .= $value.'.';
    $rand = mt_rand(0, 4);
    if ($rand == 2) {
        $out .= "\n";
    } else {
        $out .= ' ';
    }
}

You should also use mt_rand(), it is a much better version of rand() unless you like not really random results.

Upvotes: 0

Related Questions