Skip to content

Instantly share code, notes, and snippets.

@miholeus
Created December 25, 2010 18:41
Show Gist options
  • Save miholeus/754990 to your computer and use it in GitHub Desktop.
Save miholeus/754990 to your computer and use it in GitHub Desktop.
Find words in which letters are in alphabetical order
<?php
$str = "abcd 01234 87 01235 6 абвгд";
$words = preg_split("/\s/", $str, -1, PREG_SPLIT_NO_EMPTY);
function uniord($ch) {
$n = ord($ch{0});
if ($n < 128) {
return $n; // no conversion required
}
if ($n < 192 || $n > 253) {
return false; // bad first byte || out of range
}
$arr = array(1 => 192, // byte position => range from
2 => 224,
3 => 240,
4 => 248,
5 => 252,
);
foreach ($arr as $key => $val) {
if ($n >= $val) { // add byte to the 'char' array
$char[] = ord($ch{$key}) - 128;
$range = $val;
} else {
break; // save some e-trees
}
}
$retval = ($n - $range) * pow(64, sizeof($char));
foreach ($char as $key => $val) {
$pow = sizeof($char) - ($key + 1); // invert key
$retval += $val * pow(64, $pow); // dark magic
}
return $retval;
}
$found_words = array();
if(count($words) > 0) {
foreach($words as $word) {
$flag = false;
if(mb_strlen($word) == 1) {
$found_words[] = $word;
continue;
}
$chars = preg_split("//u", $word, -1, PREG_SPLIT_NO_EMPTY);
for($i = 1; $i < count($chars); $i++) {
if(uniord($chars[$i]) == (uniord($chars[$i-1]) +1)) {
$flag = true;
} else {
$flag = false;
break;
}
}
if(true === $flag) {
$found_words[] = $word;
}
}
}
var_dump($found_words);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment