Mac Taylor
Mac Taylor

Reputation: 5148

How to split string and create a random words in php

I want to suggest possible words to my clients like this :

t.est te.st tes.t te.st tes.t t.e.s.t

Now my code would be ?

<?php 

$string = "test";
$array = str_split($string);

foreach($array as $letter){
    echo $letter.".";
}

Upvotes: 1

Views: 230

Answers (1)

Vagabond
Vagabond

Reputation: 897

I hope this is solves your problem:

$string = "test";
$array = str_split($string);


$len = strlen($string);    
$rand_indx = mt_rand(0,$len);


if ($rand_indx == $len) {
    $array[$rand_indx] = ".";
} else {
    for ($x=$len; $x > $rand_indx; $x--) {
        $array[$x] = $array[$x-1];
    }
    $array[$rand_indx] = ".";
}

foreach($array as $letter){

    echo $letter;
}

Upvotes: 2

Related Questions