mirror of
https://github.com/danielstjules/Stringy.git
synced 2025-08-12 08:14:06 +02:00
Add shuffle()
This commit is contained in:
16
README.md
16
README.md
@@ -30,6 +30,7 @@ A PHP library with a variety of string manipulation functions with multibyte sup
|
||||
* [insert](#insert)
|
||||
* [truncate](#truncate)
|
||||
* [reverse](#reverse)
|
||||
* [shuffle](#shuffle)
|
||||
* [Tests](#tests)
|
||||
* [License](#license)
|
||||
|
||||
@@ -362,12 +363,19 @@ Reverses a string. A multibyte version of strrev.
|
||||
S::reverse('fòô bàř', 'UTF-8'); // 'řàb ôòf'
|
||||
```
|
||||
|
||||
##### shuffle
|
||||
|
||||
S::shuffle(string $str [, string $encoding ])
|
||||
|
||||
A multibyte str_shuffle function. It randomizes the order of characters
|
||||
in a string.
|
||||
|
||||
```php
|
||||
S::shuffle('fòô bàř', 'UTF-8') // 'àôřb òf'
|
||||
```
|
||||
|
||||
## TODO
|
||||
|
||||
**shuffle** => str_shuffle
|
||||
|
||||
**explode** => explode
|
||||
|
||||
**longestCommonPrefix**
|
||||
|
||||
**longestCommonSubstring**
|
||||
|
@@ -571,6 +571,28 @@ class Stringy {
|
||||
return $reversed;
|
||||
}
|
||||
|
||||
/**
|
||||
* A multibyte str_shuffle function. It randomizes the order of characters
|
||||
* in a string.
|
||||
*
|
||||
* @param string $str String to shuffle
|
||||
* @param string $encoding The character encoding
|
||||
* @return string The shuffled string
|
||||
*/
|
||||
public static function shuffle($str, $encoding = null) {
|
||||
$encoding = $encoding ?: mb_internal_encoding();
|
||||
|
||||
$indexes = range(0, mb_strlen($str, $encoding) - 1);
|
||||
shuffle($indexes);
|
||||
|
||||
$shuffledStr = '';
|
||||
foreach ($indexes as $i) {
|
||||
$shuffledStr .= mb_substr($str, $i, 1, $encoding);
|
||||
}
|
||||
|
||||
return $shuffledStr;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
|
@@ -632,6 +632,25 @@ class StringyTestCase extends PHPUnit_Framework_TestCase {
|
||||
return $testData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider stringsForShuffle
|
||||
*/
|
||||
public function testShuffle($string, $encoding = null) {
|
||||
// We'll just make sure that the chars are present before/after shuffle
|
||||
$result = S::shuffle($string, $encoding);
|
||||
$this->assertEquals(count_chars($string), count_chars($result));
|
||||
}
|
||||
|
||||
public function stringsForShuffle() {
|
||||
$testData = array(
|
||||
array('foo bar'),
|
||||
array('∂∆ ˚åß', 'UTF-8'),
|
||||
array('å´¥©¨ˆßå˚ ∆∂˙©å∑¥øœ¬', 'UTF-8')
|
||||
);
|
||||
|
||||
return $testData;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
|
Reference in New Issue
Block a user