John
John

Reputation: 487

Getting 2 random letters sequentially from a string

So getting 2 random letters from a string is easy enough to find an answer to:

$var1 = substr(str_shuffle(str_repeat($var1, 2)), 0, 2);

But what if you want to get 2 letters sequentially from a string,Is there a way to do it without using a loop?

For instance, if you have a string named "Colorado", and if the first random character grabbed was "r", it would only get a letter from the remaining 3 letters for the 2nd chosen letter.

Upvotes: 1

Views: 49

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

There is most likely other ways, here is one.

Pick random char, use stristr, shuffle it then grab first 2 chars.

<?php
$var = 'Colorado';

// pick random
$picked = $var[rand(0, strlen($var))];

// grab string after first occurrence
$parts = stristr($var, $picked);

// shuffle it
$part = str_shuffle($parts);

echo $part[0].$part[1];

https://3v4l.org/uDvRX

*your need to add some undefined checks to handle no matches etc

Upvotes: 1

Related Questions