TextAnalysisLib.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. }
  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. * @return array(char=>amount) for empty char or int amount for specific char
  149. * 2010-08-31 ms
  150. */
  151. public function maxOccurrences($caseSensitive = false) {
  152. $arr = $this->occurrences(null, $caseSensitive);
  153. $max = 0;
  154. $occ = array();
  155. foreach ($arr as $key => $value) {
  156. if ($value === $max) {
  157. $occ[$key] = $value;
  158. } elseif ($value > $max) {
  159. $max = $value;
  160. $occ = array($key => $value);
  161. }
  162. }
  163. //echo returns($occ);
  164. return $occ;
  165. }
  166. public function getLength() {
  167. if (!$this->lenght) {
  168. $this->lenght = mb_strlen($this->text);
  169. }
  170. return $this->lenght;
  171. }
  172. public function getCharacter() {
  173. if (!$this->char) $this->char = mb_strlen(strtr($this->text, array("\n" => '', "\r" =>
  174. '')));
  175. return $this->char;
  176. }
  177. public function getLetter() {
  178. if (!$this->letter) {
  179. $l_text = mb_strtolower($this->text);
  180. for ($i = 0; $i < $this->lenght; $i++)
  181. if (mb_strpos("abcdefghijklmnopqrstuvwxyzäöü", $l_text[$i]) != false) $this->
  182. letter++;
  183. }
  184. return $this->letter;
  185. }
  186. public function getSpace() {
  187. if (!$this->space) $this->space = mb_substr_count($this->text, " ") +
  188. mb_substr_count($this->text, "\t");
  189. return $this->space;
  190. }
  191. public function getSymbol() {
  192. return $this->getCharacter() - $this->getLetter() - $this->getSpace();
  193. }
  194. //TODO: improve it to work with case insensitivity and utf8 chars like é or î
  195. public function getWord($parse = false) {
  196. if (!$this->word && !$this->r_word) {
  197. @preg_match_all("/[A-Za-zäöüÄÖÜß\-'\\\"]+/", $this->text, $m);
  198. $this->word = count($m[0]);
  199. $this->r_word = $m[0];
  200. }
  201. return $parse ? $this->r_word : $this->word;
  202. }
  203. /**
  204. * @param options
  205. * - min_char, max_char, case_sensititive, sort ('asc', 'desc', 'length', 'alpha', false), limit...
  206. * 2010-10-09 ms
  207. */
  208. public function wordCount($options = array()) {
  209. if (true || !$this->rr_word) {
  210. $text = str_replace(array(NL, CR, PHP_EOL, TB), ' ', $this->text);
  211. $res = array();
  212. $search = array('*', '+', '~', ',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '“', '”', '—', '"', '‘', '’', '!', '?', '<', '>', '=', '/');
  213. $search = array_merge($search, array(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->r_sen) {
  253. @preg_match_all("/[^:|;|\!|\.]+(:|;|\!|\.| )+/", $this->text, $m);
  254. $this->sen = count($m[0]);
  255. foreach ($m[0] as $s) $this->r_sen[] = strtr(trim($s), array("\n" => '', "\r" =>
  256. ''));
  257. }
  258. return $parse ? $this->r_sen : $this->sen;
  259. }
  260. public function getParagraph($parse = false) {
  261. if (!$this->para && !$this->r_para) {
  262. @preg_match_all("/[^\n]+?(:|;|\!|\.| )+\n/s", strtr($this->text, array("\r" =>
  263. '')) . "\n", $m);
  264. $this->para = count($m[0]);
  265. foreach ($m[0] as $p) $this->r_para[] = trim($p);
  266. }
  267. return $parse ? $this->r_para : $this->para;
  268. }
  269. public function beautify($wordwrap = false) {
  270. if (!$this->beautified) {
  271. $this->beautified = @preg_replace(array("/ {1,}/", "/\. {1,}\./", "/\. *(?!\.)/",
  272. "/(,|:|;|\!|\)) */", "/(,|:|;|\!|\)|\.) *\r\n/", "/(\r\n) {3,}/"), array(" ", ".",
  273. ". ", "$1 ", "$1\r\n", "\r\n\r\n"), $this->text);
  274. }
  275. return $wordwrap ? wordwrap($this->beautified, $wordwrap) : $this->beautified;
  276. }
  277. }