phprandomreplace

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?


Solution

  • 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.