TextAnalysisLib.php 7.4 KB

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