Getting 2 random letters sequentially from a string

John :

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 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 "Colorado", if the first random character it grabbed was "r", it would only get a letter from the remaining 3 for the 2nd.

Lawrence Cherone :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198386&siteId=1