TextAnalysisLib.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. App::uses('TextLib', 'Tools.Utility');
  3. /**
  4. * TODO: extend the core String class some day?
  5. *
  6. * 2010-08-31 ms
  7. */
  8. class TextAnalysisLib extends TextLib {
  9. protected $text, $lenght, $char, $letter, $space, $word, $r_word, $sen, $r_sen, $para,
  10. $r_para, $beautified;
  11. public function __construct($text = null) {
  12. $this->text = $text;
  13. }
  14. /**
  15. * @param string $stringToCheck
  16. * @param tolerance (in %: 0 ... 1)
  17. * @return boolean $success
  18. * 2011-10-13 ms
  19. */
  20. public function isScreamFont($str = null, $tolerance = 0.4) {
  21. if ($str === null) {
  22. $str = $this->text;
  23. }
  24. if (empty($str)) {
  25. return false;
  26. }
  27. $res = preg_match_all('/[A-ZÄÖÜ]/u', $str, $uppercase);
  28. $uppercase = array_shift($uppercase);
  29. //echo returns($uppercase);
  30. $res = preg_match_all('/[a-zäöüß]/u', $str, $lowercase);
  31. $lowercase = array_shift($lowercase);
  32. //echo returns($lowercase);
  33. if (($countUpper = count($uppercase)) && $countUpper >= count($lowercase)) {
  34. return true;
  35. }
  36. //TODO: tolerance
  37. return false;
  38. }
  39. /**
  40. * @param string
  41. * @param string $additionalChars
  42. * - e.g. `-()0123456789`
  43. */
  44. public function isWord($str = null, $additionalChars = null) {
  45. return preg_match('/^\w+$/', $str);
  46. }
  47. /* utf8 generell stuff */
  48. /**
  49. * Tests whether a string contains only 7-bit ASCII bytes. This is used to
  50. * determine when to use native functions or UTF-8 functions.
  51. *
  52. * $ascii = UTF8::is_ascii($str);
  53. *
  54. * @param string string to check
  55. * @return bool
  56. */
  57. public function isAscii($str = null) {
  58. if ($str === null) {
  59. $str = $this->text;
  60. }
  61. return !preg_match('/[^\x00-\x7F]/S', $str);
  62. }
  63. /**
  64. * Strips out device control codes in the ASCII range.
  65. *
  66. * $str = UTF8::strip_ascii_ctrl($str);
  67. *
  68. * @param string string to clean
  69. * @return string
  70. */
  71. public function stripAsciiCtrl($str = null) {
  72. if ($str === null) {
  73. $str = $this->text;
  74. }
  75. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $str);
  76. }
  77. /**
  78. * Strips out all non-7bit ASCII bytes.
  79. *
  80. * $str = UTF8::strip_non_ascii($str);
  81. *
  82. * @param string string to clean
  83. * @return string
  84. */
  85. public function stripNonAscii($str = null) {
  86. if ($str === null) {
  87. $str = $this->text;
  88. }
  89. return preg_replace('/[^\x00-\x7F]+/S', '', $str);
  90. }
  91. public function convertToOrd($str = null, $separator = '-') {
  92. /*
  93. if (!class_exists('UnicodeLib')) {
  94. App::uses('UnicodeLib', 'Tools.Lib');
  95. }
  96. */
  97. if ($str === null) {
  98. $str = $this->text;
  99. }
  100. $chars = preg_split('//', $str, -1);
  101. $res = array();
  102. foreach ($chars as $char) {
  103. //$res[] = UnicodeLib::ord($char);
  104. $res[] = ord($char);
  105. }
  106. return implode($separator, $res);
  107. }
  108. /* text object specific */
  109. /**
  110. * @return array(char=>amount) for empty char or int amount for specific char
  111. * 2010-08-31 ms
  112. */
  113. public function occurrences($char = null, $caseSensitive = false) {
  114. if ($caseSensitive) {
  115. $str = $this->text;
  116. } else {
  117. if ($char !== null) {
  118. $char = strtolower($char);
  119. }
  120. $str = strtolower($this->text);
  121. }
  122. if ($char === null) {
  123. $occ = array();
  124. $str = str_split($str);
  125. foreach ($str as $value) {
  126. if (array_key_exists($value, $occ)) {
  127. $occ[$value] += 1;
  128. } else {
  129. $occ[$value] = 1;
  130. }
  131. }
  132. return $occ;
  133. } else {
  134. $occ = 0;
  135. $pos = 0;
  136. do {
  137. $pos = strpos($str, $char, $pos);
  138. if ($pos !== false) {
  139. $occ++;
  140. $pos++;
  141. } else {
  142. break;
  143. }
  144. } while (true);
  145. return $occ;
  146. }
  147. }
  148. /**
  149. * @return array(char=>amount) for empty char or int amount for specific char
  150. * 2010-08-31 ms
  151. */
  152. public function maxOccurrences($caseSensitive = false) {
  153. $arr = $this->occurrences(null, $caseSensitive);
  154. $max = 0;
  155. $occ = array();
  156. foreach ($arr as $key => $value) {
  157. if ($value === $max) {
  158. $occ[$key] = $value;
  159. } elseif ($value > $max) {
  160. $max = $value;
  161. $occ = array($key => $value);
  162. }
  163. }
  164. echo returns($occ);
  165. return $occ;
  166. }
  167. public function getLength() {
  168. if (!$this->lenght) {
  169. $this->lenght = mb_strlen($this->text);
  170. }
  171. return $this->lenght;
  172. }
  173. public function getCharacter() {
  174. if (!$this->char) $this->char = mb_strlen(strtr($this->text, array("\n" => '', "\r" =>
  175. '')));
  176. return $this->char;
  177. }
  178. public function getLetter() {
  179. if (!$this->letter) {
  180. $l_text = mb_strtolower($this->text);
  181. for ($i = 0; $i < $this->lenght; $i++)
  182. if (mb_strpos("abcdefghijklmnopqrstuvwxyzäöü", $l_text[$i]) != false) $this->
  183. letter++;
  184. }
  185. return $this->letter;
  186. }
  187. public function getSpace() {
  188. if (!$this->space) $this->space = mb_substr_count($this->text, " ") +
  189. mb_substr_count($this->text, "\t");
  190. return $this->space;
  191. }
  192. public function getSymbol() {
  193. return $this->getCharacter() - $this->getLetter() - $this->getSpace();
  194. }
  195. //TODO: improve it to work with case insensitivity and utf8 chars like é or î
  196. public function getWord($parse = false) {
  197. if (!$this->word && !$this->r_word) {
  198. @preg_match_all("/[A-Za-zäöüÄÖÜß\-'\\\"]+/", $this->text, $m);
  199. $this->word = count($m[0]);
  200. $this->r_word = $m[0];
  201. }
  202. return $parse ? $this->r_word : $this->word;
  203. }
  204. /**
  205. * @param options
  206. * - min_char, max_char, case_sensititive, sort ('asc', 'desc', 'length', 'alpha', false), limit...
  207. * 2010-10-09 ms
  208. */
  209. public function wordCount($options = array()) {
  210. if (true || !$this->rr_word) {
  211. $text = str_replace(array(NL, CR, PHP_EOL, TB), ' ', $this->text);
  212. $res = array();
  213. $search = array('*', '+', '~', ',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '“', '”', '—', '"', '‘', '’', '!', '?', '<', '>', '=', '/');
  214. $search = array_merge($search, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
  215. $text = str_replace($search, ' ', $text);
  216. $pieces = explode(' ', $text);
  217. //TODO: use array_count_values()?
  218. foreach ($pieces as $key => $piece) {
  219. if (empty($options['case_sensitive'])) {
  220. $piece = mb_strtolower($piece);
  221. }
  222. $piece = trim($piece);
  223. if (empty($piece) || !empty($options['min_char']) && mb_strlen($piece) < $options['min_char'] || !empty($options['max_char']) && mb_strlen($piece) > $options['max_char']) {
  224. unset($pieces[$key]);
  225. continue;
  226. }
  227. if (!array_key_exists($piece, $res)) {
  228. $res[$piece] = 0;
  229. }
  230. $res[$piece]++;
  231. }
  232. if (!empty($options['sort'])) {
  233. $sort = strtolower($options['sort']);
  234. if ($sort === 'asc') {
  235. asort($res);
  236. } elseif ($sort === 'desc') {
  237. arsort($res);
  238. } elseif ($sort === 'length') {
  239. //TODO:
  240. //uasort($res, $callback);
  241. } elseif ($sort === 'alpha') {
  242. ksort($res);
  243. }
  244. }
  245. if (!empty($options['limit'])) {
  246. $res = array_slice($res, 0, (int)$options['limit'], true);
  247. }
  248. //$this->rr_word = $res;
  249. }
  250. return $res; // $this->rr_word;
  251. }
  252. public function getSentence($parse = false) {
  253. if (!$this->sen && !$this->r_sen) {
  254. @preg_match_all("/[^:|;|\!|\.]+(:|;|\!|\.| )+/", $this->text, $m);
  255. $this->sen = count($m[0]);
  256. foreach ($m[0] as $s) $this->r_sen[] = strtr(trim($s), array("\n" => '', "\r" =>
  257. ''));
  258. }
  259. return $parse ? $this->r_sen : $this->sen;
  260. }
  261. public function getParagraph($parse = false) {
  262. if (!$this->para && !$this->r_para) {
  263. @preg_match_all("/[^\n]+?(:|;|\!|\.| )+\n/s", strtr($this->text, array("\r" =>
  264. '')) . "\n", $m);
  265. $this->para = count($m[0]);
  266. foreach ($m[0] as $p) $this->r_para[] = trim($p);
  267. }
  268. return $parse ? $this->r_para : $this->para;
  269. }
  270. public function beautify($wordwrap = false) {
  271. if (!$this->beautified) {
  272. $this->beautified = @preg_replace(array("/ {1,}/", "/\. {1,}\./", "/\. *(?!\.)/",
  273. "/(,|:|;|\!|\)) */", "/(,|:|;|\!|\)|\.) *\r\n/", "/(\r\n) {3,}/"), array(" ", ".",
  274. ". ", "$1 ", "$1\r\n", "\r\n\r\n"), $this->text);
  275. }
  276. return $wordwrap ? wordwrap($this->beautified, $wordwrap) : $this->beautified;
  277. }
  278. }