-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathT9.php
83 lines (73 loc) · 2.31 KB
/
T9.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
* T9 Misunderstanding Generator
* Copyright (c) 2012 by Alec Smecher
*
* Given text input, generate all the possible T9 (predictive texting)
* misunderstandings that might come from a phone's auto-suggest, using a
* dictionary text file as a source of possible misunderstandings.
*
* Distributed under the GNU GPL v2. For full terms see the file COPYING.
*/
define('DICTIONARY_PATH', '/usr/share/dict/american-english');
class T9Confuzzler {
/** @var $dictionary array Array of T9-hashed word lists for finding collisions */
var $dictionary;
/**
* Constructor
*/
function T9Confuzzler() {
$this->dictionary = array();
}
/**
* Translate a word into its T9 equivalent (that is, what you'd type on the keypad)
* @param $word string
* @return string
*/
static function calculateT9($word) {
return strtr(strtoupper($word), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '22233344455566677778889999');
}
/**
* Add a word list to the current set.
* @param $filename string Filename containing word list, one word per line.
*/
function addDictionary($filename) {
foreach (file($filename) as $word) {
$word = trim($word);
$this->dictionary[$this->calculateT9($word)][] = $word;
}
}
/**
* Get the potential misunderstandings of a word, if any.
* @param $word string Single T9 word
* @param $dictionary Lookup array of potential misunderstandings in T9 format
* @return string "{A, B, C}" if A, B, C are potential misunderstandings; "A" if none possible
*/
function getMisunderstandings($word) {
$t9 = $this->calculateT9($word);
if (isset($this->dictionary[$t9])) {
return '{' . join(', ', $this->dictionary[$t9]) . '}';
} else {
return $word;
}
}
/**
* Replace misunderstandings in a string; this function is only useful
* as a callback for preg_match_callback.
* @param $match array
* @return string
*/
function replace_callback($match) {
return $this->getMisunderstandings($match[0], $this->dictionary);
}
};
// Load and store the dictionary, T9'ed, as a lookup table.
$t9Confuzzler = new T9Confuzzler();
$t9Confuzzler->addDictionary(DICTIONARY_PATH);
// While there's data on standard input, confuzzle it.
$fp = fopen('php://stdin', 'r');
while (!feof($fp)) {
echo preg_replace_callback('/[a-zA-Z]+/', array($t9Confuzzler, 'replace_callback'), fgets($fp));
};
fclose($fp);
?>