Skip to content

Instantly share code, notes, and snippets.

@carlosdagos
Last active February 5, 2016 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosdagos/6755ad994da07a7b4959 to your computer and use it in GitHub Desktop.
Save carlosdagos/6755ad994da07a7b4959 to your computer and use it in GitHub Desktop.
<?php
define('DEBUG', isset($argv[2]) && strtolower($argv[2]) == '--debug'); // just set the last one to "--debug"
$locale = explode('.', getenv('LC_ALL'))[1];
echo sprintf('System locale: %s [mb_internal_encoding set to: %s]' . "\n", getenv('LC_ALL'), $locale);
function rotateStringSimple(string $str) : string {
$res = '';
if (DEBUG) echo sprintf('%s String length: %s' . "\n", __FUNCTION__, strlen($str));
for ($i = 0; $i < strlen($str); $i++) {
$chr = $str{$i};
$res = $chr . $res;
if (DEBUG) {
echo sprintf('%s: Rotated hex value: %s [%s]' . "\n", __FUNCTION__, bin2hex($chr), $chr);
}
}
return $res;
}
function rotateStringMb(string $str) : string {
$res = '';
if (DEBUG) echo sprintf('%s String length: %s' . "\n", __FUNCTION__, mb_strlen($str));
for ($i = 0; $i < mb_strlen($str); $i++) {
$chr = mb_substr($str, $i, 1);
$res = $chr . $res;
if (DEBUG) {
echo sprintf('%s: Rotated hex value: %s [%s]' . "\n", __FUNCTION__, bin2hex($chr), $chr);
}
}
return $res;
}
/**
* This one will work for this purpose
*/
function rotateStringGrapheme(string $str) : string {
$res = '';
if (DEBUG) echo sprintf('%s: String length: %s' . "\n", __FUNCTION__, grapheme_strlen($str));
for ($i = 0; $i < grapheme_strlen($str); $i++) {
$chr = grapheme_substr($str, $i, 1);
$res = $chr . $res;
if (DEBUG) {
echo sprintf('%s: Rotated hex value: %s [%s]' . "\n", __FUNCTION__, bin2hex($chr), $chr);
}
}
return $res;
}
$str = $argv[1]; // shell call: $ ~ php script.php argument -- "argument" is in the 2nd pos
echo sprintf('Your string reversed (sb): %s' . "\n", rotateStringSimple($str));
echo sprintf('Your string reversed (mb): %s' . "\n", rotateStringMb($str));
echo sprintf('Your string reversed (gp): %s' . "\n", rotateStringGrapheme($str));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment