forked from marshallbrekka/WebBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringIndexer.php
103 lines (76 loc) · 1.92 KB
/
StringIndexer.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* StringIndexer
*
* @author Marshall
*/
class StringIndexer {
private $positionsOfWordIndex = array();
private $wordAtPositionIndex = array();
private $string;
private $stringLength;
private $lastIndex = 0;
private $wordIndex = 0;
public function indexString($string) {
$this->resetVariables();
$this->string = trim($string);
$this->stringLength = strlen($string);
$word = $this->getNextWord();
while($word) {
$this->logWord($word);
$word = $this->getNextWord();
}
}
private function resetVariables() {
$this->lastIndex = 0;
$this->wordIndex = 0;
$this->positionsOfWordIndex = array();
$this->wordAtPositionIndex = array();
}
private function getNextWord() {
if($this->lastIndex == $this->stringLength) {
return false;
}
$index = strpos($this->string , ' ', $this->lastIndex + 1);
$length = $this->getWordLength($index);
if($length) {
$word = substr($this->string, $this->lastIndex, $length);
$this->lastIndex += $length;
return trim($word);
} else {
return false;
}
}
private function getWordLength($index) {
$length = 0;
if($index) {
$length = $index - $this->lastIndex;
} else if($this->stringLength - $index) {
$length = $this->stringLength - $this->lastIndex;
}
return $length;
}
private function logWord($word) {
$comma = '';
$this->positionsOfWordIndex[$word];
if(!empty($this->positionsOfWordIndex[$word])) {
$comma = ',';
}
$this->positionsOfWordIndex[$word] .= $comma . $this->wordIndex;
$this->wordAtPositionIndex[$this->wordIndex] = &$word;
$this->wordIndex++;
}
public function getIndexArrayOfWord($word) {
if(isset($this->positionsOfWordIndex[$word])) {
return explode(',', $this->positionsOfWordIndex[$word]);
}
return false;
}
public function getWordAtIndex($index) {
if(isset($this->wordAtPositionIndex[$index])) {
return $this->wordAtPositionIndex[$index];
}
return false;
}
}
?>