TextLib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. <?php
  2. /**
  3. * TODO: extend the core String class some day?
  4. *
  5. * 2010-08-31 ms
  6. */
  7. class TextLib {
  8. protected $text, $lenght, $char, $letter, $space, $word, $r_word, $sen, $r_sen, $para,
  9. $r_para, $beautified;
  10. public function __construct($text) {
  11. $this->text = $text;
  12. }
  13. /**
  14. * @param string $stringToCheck
  15. * @param tolerance (in %: 0 ... 1)
  16. * @return boolean $success
  17. * 2011-10-13 ms
  18. */
  19. public function isScreamFont($str = null, $tolerance = 0.4) {
  20. if ($str === null) {
  21. $str = $this->text;
  22. }
  23. if (empty($str)) {
  24. return false;
  25. }
  26. $res = preg_match_all('/[A-ZÄÖÜ]/u', $str, $uppercase);
  27. $uppercase = array_shift($uppercase);
  28. //echo returns($uppercase);
  29. $res = preg_match_all('/[a-zäöüß]/u', $str, $lowercase);
  30. $lowercase = array_shift($lowercase);
  31. //echo returns($lowercase);
  32. if (($countUpper = count($uppercase)) && $countUpper >= count($lowercase)) {
  33. return true;
  34. }
  35. //TODO: tolerance
  36. return false;
  37. }
  38. /**
  39. * @param string
  40. * @param string $additionalChars
  41. * - e.g. `-()0123456789`
  42. */
  43. public function isWord($str = null, $additionalChars = null) {
  44. return preg_match('/^\w+$/', $str);
  45. }
  46. /* utf8 generell stuff */
  47. /**
  48. * Tests whether a string contains only 7-bit ASCII bytes. This is used to
  49. * determine when to use native functions or UTF-8 functions.
  50. *
  51. * $ascii = UTF8::is_ascii($str);
  52. *
  53. * @param string string to check
  54. * @return bool
  55. */
  56. public function isAscii($str = null) {
  57. if ($str === null) {
  58. $str = $this->text;
  59. }
  60. return !preg_match('/[^\x00-\x7F]/S', $str);
  61. }
  62. /**
  63. * Strips out device control codes in the ASCII range.
  64. *
  65. * $str = UTF8::strip_ascii_ctrl($str);
  66. *
  67. * @param string string to clean
  68. * @return string
  69. */
  70. public function stripAsciiCtrl($str = null) {
  71. if ($str === null) {
  72. $str = $this->text;
  73. }
  74. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $str);
  75. }
  76. /**
  77. * Strips out all non-7bit ASCII bytes.
  78. *
  79. * $str = UTF8::strip_non_ascii($str);
  80. *
  81. * @param string string to clean
  82. * @return string
  83. */
  84. public function stripNonAscii($str = null) {
  85. if ($str === null) {
  86. $str = $this->text;
  87. }
  88. return preg_replace('/[^\x00-\x7F]+/S', '', $str);
  89. }
  90. public function convertToOrd($str = null, $separator = '-') {
  91. /*
  92. if (!class_exists('UnicodeLib')) {
  93. App::uses('UnicodeLib', 'Tools.Lib');
  94. }
  95. */
  96. if ($str === null) {
  97. $str = $this->text;
  98. }
  99. $chars = preg_split('//', $str, -1);
  100. $res = array();
  101. foreach ($chars as $char) {
  102. //$res[] = UnicodeLib::ord($char);
  103. $res[] = ord($char);
  104. }
  105. return implode($separator, $res);
  106. }
  107. public function convertToOrdTable($str) {
  108. $res = '<table><tr>';
  109. $r = array('chr'=>array(), 'ord'=>array());
  110. $chars = preg_split('//', $str, -1);
  111. foreach ($chars as $char) {
  112. //$res[] = UnicodeLib::ord($char);
  113. $r['ord'][] = ord($char);
  114. $r['chr'][] = $char;
  115. }
  116. $res .= '<th>'.implode('</th><th>', $r['chr']).'</th>';
  117. $res .= '</tr>';
  118. $res .= '<tr>';
  119. $res .= '<td>'.implode('</th><th>', $r['ord']).'</td>';
  120. $res .= '</tr></table>';
  121. return $res;
  122. }
  123. /* other */
  124. /**
  125. * Explode a string of given tags into an array.
  126. */
  127. public function explodeTags($tags) {
  128. // This regexp allows the following types of user input:
  129. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  130. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  131. preg_match_all($regexp, $tags, $matches);
  132. $typed_tags = array_unique($matches[1]);
  133. $tags = array();
  134. foreach ($typed_tags as $tag) {
  135. // If a user has escaped a term (to demonstrate that it is a group,
  136. // or includes a comma or quote character), we remove the escape
  137. // formatting so to save the term into the database as the user intends.
  138. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  139. if ($tag != "") {
  140. $tags[] = $tag;
  141. }
  142. }
  143. return $tags;
  144. }
  145. /**
  146. * Implode an array of tags into a string.
  147. */
  148. public function implodeTags($tags) {
  149. $encoded_tags = array();
  150. foreach ($tags as $tag) {
  151. // Commas and quotes in tag names are special cases, so encode them.
  152. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  153. $tag = '"'. str_replace('"', '""', $tag) .'"';
  154. }
  155. $encoded_tags[] = $tag;
  156. }
  157. return implode(', ', $encoded_tags);
  158. }
  159. /**
  160. * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin)
  161. * by inserting a non-breaking space between the last two words.
  162. *
  163. * echo Text::widont($text);
  164. *
  165. * @param string text to remove widows from
  166. * @return string
  167. */
  168. public function widont($str = null) {
  169. if ($str === null) {
  170. $str = $this->text;
  171. }
  172. $str = rtrim($str);
  173. $space = strrpos($str, ' ');
  174. if ($space !== FALSE) {
  175. $str = substr($str, 0, $space).'&nbsp;'.substr($str, $space + 1);
  176. }
  177. return $str;
  178. }
  179. /* text object specific */
  180. /**
  181. * @return array(char=>amount) for empty char or int amount for specific char
  182. * 2010-08-31 ms
  183. */
  184. public function occurrences($char = null, $caseSensitive = false) {
  185. if ($caseSensitive) {
  186. $str = $this->text;
  187. } else {
  188. if ($char !== null) {
  189. $char = strtolower($char);
  190. }
  191. $str = strtolower($this->text);
  192. }
  193. if ($char === null) {
  194. $occ = array();
  195. $str = str_split($str);
  196. foreach ($str as $value) {
  197. if (array_key_exists($value, $occ)) {
  198. $occ[$value] += 1;
  199. } else {
  200. $occ[$value] = 1;
  201. }
  202. }
  203. return $occ;
  204. } else {
  205. $occ = 0;
  206. $pos = 0;
  207. do {
  208. $pos = strpos($str, $char, $pos);
  209. if ($pos !== false) {
  210. $occ++;
  211. $pos++;
  212. } else {
  213. break;
  214. }
  215. } while (true);
  216. return $occ;
  217. }
  218. }
  219. /**
  220. * @return array(char=>amount) for empty char or int amount for specific char
  221. * 2010-08-31 ms
  222. */
  223. public function maxOccurrences($caseSensitive = false) {
  224. $arr = $this->occurrences(null, $caseSensitive);
  225. $max = 0;
  226. $occ = array();
  227. foreach ($arr as $key => $value) {
  228. if ($value === $max) {
  229. $occ[$key] = $value;
  230. } elseif ($value > $max) {
  231. $max = $value;
  232. $occ = array($key => $value);
  233. }
  234. }
  235. echo returns($occ);
  236. return $occ;
  237. }
  238. public function getLength() {
  239. if (!$this->lenght) {
  240. $this->lenght = mb_strlen($this->text);
  241. }
  242. return $this->lenght;
  243. }
  244. public function getCharacter() {
  245. if (!$this->char) $this->char = mb_strlen(strtr($this->text, array("\n" => '', "\r" =>
  246. '')));
  247. return $this->char;
  248. }
  249. public function getLetter() {
  250. if (!$this->letter) {
  251. $l_text = mb_strtolower($this->text);
  252. for ($i = 0; $i < $this->lenght; $i++)
  253. if (mb_strpos("abcdefghijklmnopqrstuvwxyzäöü", $l_text[$i]) != false) $this->
  254. letter++;
  255. }
  256. return $this->letter;
  257. }
  258. public function getSpace() {
  259. if (!$this->space) $this->space = mb_substr_count($this->text, " ") +
  260. mb_substr_count($this->text, "\t");
  261. return $this->space;
  262. }
  263. public function getSymbol() {
  264. return $this->getCharacter() - $this->getLetter() - $this->getSpace();
  265. }
  266. //TODO: improve it to work with case insensitivity and utf8 chars like é or î
  267. public function getWord($parse = false) {
  268. if (!$this->word && !$this->r_word) {
  269. @preg_match_all("/[A-Za-zäöüÄÖÜß\-'\\\"]+/", $this->text, $m);
  270. $this->word = count($m[0]);
  271. $this->r_word = $m[0];
  272. }
  273. return $parse ? $this->r_word : $this->word;
  274. }
  275. /**
  276. * @param options
  277. * - min_char, max_char, case_sensititive, ...
  278. * 2010-10-09 ms
  279. */
  280. public function words($options = array()) {
  281. if (true || !$this->xr_word) {
  282. $text = str_replace(array(PHP_EOL, NL, TB), ' ', $this->text);
  283. $pieces = explode(' ', $text);
  284. $pieces = array_unique($pieces);
  285. # strip chars like . or ,
  286. foreach ($pieces as $key => $piece) {
  287. if (empty($options['case_sensitive'])) {
  288. $piece = mb_strtolower($piece);
  289. }
  290. $search = array(',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '"', '!', '?', '<', '>', '=', '/');
  291. $search = array_merge($search, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
  292. $piece = str_replace($search, '', $piece);
  293. $piece = trim($piece);
  294. if (empty($piece) || !empty($options['min_char']) && mb_strlen($piece) < $options['min_char'] || !empty($options['max_char']) && mb_strlen($piece) > $options['max_char']) {
  295. unset($pieces[$key]);
  296. } else {
  297. $pieces[$key] = $piece;
  298. }
  299. }
  300. $pieces = array_unique($pieces);
  301. //$this->xr_word = $pieces;
  302. }
  303. return $pieces;
  304. }
  305. /**
  306. * @param options
  307. * - min_char, max_char, case_sensititive, sort ('asc', 'desc', 'length', 'alpha', false), limit...
  308. * 2010-10-09 ms
  309. */
  310. public function wordCount($options = array()) {
  311. if (true || !$this->rr_word) {
  312. $text = str_replace(array(NL, CR, PHP_EOL, TB), ' ', $this->text);
  313. $res = array();
  314. $search = array('*', '+', '~', ',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '“', '”', '—', '"', '‘', '’', '!', '?', '<', '>', '=', '/');
  315. $search = array_merge($search, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
  316. $text = str_replace($search, ' ', $text);
  317. $pieces = explode(' ', $text);
  318. //TODO: use array_count_values()?
  319. foreach ($pieces as $key => $piece) {
  320. if (empty($options['case_sensitive'])) {
  321. $piece = mb_strtolower($piece);
  322. }
  323. $piece = trim($piece);
  324. if (empty($piece) || !empty($options['min_char']) && mb_strlen($piece) < $options['min_char'] || !empty($options['max_char']) && mb_strlen($piece) > $options['max_char']) {
  325. unset($pieces[$key]);
  326. continue;
  327. }
  328. if (!array_key_exists($piece, $res)) {
  329. $res[$piece] = 0;
  330. }
  331. $res[$piece]++;
  332. }
  333. if (!empty($options['sort'])) {
  334. $sort = strtolower($options['sort']);
  335. if ($sort == 'asc') {
  336. asort($res);
  337. } elseif ($sort == 'desc') {
  338. arsort($res);
  339. } elseif ($sort == 'length') {
  340. //TODO:
  341. //uasort($res, $callback);
  342. } elseif ($sort == 'alpha') {
  343. ksort($res);
  344. }
  345. }
  346. if (!empty($options['limit'])) {
  347. $res = array_slice($res, 0, (int)$options['limit'], true);
  348. }
  349. //$this->rr_word = $res;
  350. }
  351. return $res; // $this->rr_word;
  352. }
  353. public function getSentence($parse = false) {
  354. if (!$this->sen && !$this->r_sen) {
  355. @preg_match_all("/[^:|;|\!|\.]+(:|;|\!|\.| )+/", $this->text, $m);
  356. $this->sen = count($m[0]);
  357. foreach ($m[0] as $s) $this->r_sen[] = strtr(trim($s), array("\n" => '', "\r" =>
  358. ''));
  359. }
  360. return $parse ? $this->r_sen : $this->sen;
  361. }
  362. public function getParagraph($parse = false) {
  363. if (!$this->para && !$this->r_para) {
  364. @preg_match_all("/[^\n]+?(:|;|\!|\.| )+\n/s", strtr($this->text, array("\r" =>
  365. '')) . "\n", $m);
  366. $this->para = count($m[0]);
  367. foreach ($m[0] as $p) $this->r_para[] = trim($p);
  368. }
  369. return $parse ? $this->r_para : $this->para;
  370. }
  371. public function beautify($wordwrap = false) {
  372. if (!$this->beautified) {
  373. $this->beautified = @preg_replace(array("/ {1,}/", "/\. {1,}\./", "/\. *(?!\.)/",
  374. "/(,|:|;|\!|\)) */", "/(,|:|;|\!|\)|\.) *\r\n/", "/(\r\n) {3,}/"), array(" ", ".",
  375. ". ", "$1 ", "$1\r\n", "\r\n\r\n"), $this->text);
  376. }
  377. return $wordwrap ? wordwrap($this->beautified, $wordwrap) : $this->beautified;
  378. }
  379. /**
  380. * High ASCII to Entities
  381. *
  382. * Converts High ascii text and MS Word special characters to character entities
  383. *
  384. * @access public
  385. * @param string
  386. * @return string
  387. */
  388. public function ascii_to_entities($str) {
  389. $count = 1;
  390. $out = '';
  391. $temp = array();
  392. for ($i = 0, $s = strlen($str); $i < $s; $i++) {
  393. $ordinal = ord($str[$i]);
  394. if ($ordinal < 128) {
  395. /*
  396. If the $temp array has a value but we have moved on, then it seems only
  397. fair that we output that entity and restart $temp before continuing. -Paul
  398. */
  399. if (count($temp) == 1) {
  400. $out .= '&#' . array_shift($temp) . ';';
  401. $count = 1;
  402. }
  403. $out .= $str[$i];
  404. } else {
  405. if (count($temp) == 0) {
  406. $count = ($ordinal < 224) ? 2 : 3;
  407. }
  408. $temp[] = $ordinal;
  409. if (count($temp) == $count) {
  410. $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] %
  411. 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
  412. $out .= '&#' . $number . ';';
  413. $count = 1;
  414. $temp = array();
  415. }
  416. }
  417. }
  418. return $out;
  419. }
  420. // ------------------------------------------------------------------------
  421. /**
  422. * Entities to ASCII
  423. *
  424. * Converts character entities back to ASCII
  425. *
  426. * @access public
  427. * @param string
  428. * @param bool
  429. * @return string
  430. */
  431. public function entities_to_ascii($str, $all = true) {
  432. if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) {
  433. for ($i = 0, $s = count($matches['0']); $i < $s; $i++) {
  434. $digits = $matches['1'][$i];
  435. $out = '';
  436. if ($digits < 128) {
  437. $out .= chr($digits);
  438. } elseif ($digits < 2048) {
  439. $out .= chr(192 + (($digits - ($digits % 64)) / 64));
  440. $out .= chr(128 + ($digits % 64));
  441. } else {
  442. $out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
  443. $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
  444. $out .= chr(128 + ($digits % 64));
  445. }
  446. $str = str_replace($matches['0'][$i], $out, $str);
  447. }
  448. }
  449. if ($all) {
  450. $str = str_replace(array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"),
  451. array("&", "<", ">", "\"", "'", "-"), $str);
  452. }
  453. return $str;
  454. }
  455. /**
  456. * Reduce Double Slashes
  457. *
  458. * Converts double slashes in a string to a single slash,
  459. * except those found in http://
  460. *
  461. * http://www.some-site.com//index.php
  462. *
  463. * becomes:
  464. *
  465. * http://www.some-site.com/index.php
  466. *
  467. * @access public
  468. * @param string
  469. * @return string
  470. */
  471. public function reduce_double_slashes($str) {
  472. return preg_replace("#([^:])//+#", "\\1/", $str);
  473. }
  474. // ------------------------------------------------------------------------
  475. /**
  476. * Reduce Multiples
  477. *
  478. * Reduces multiple instances of a particular character. Example:
  479. *
  480. * Fred, Bill,, Joe, Jimmy
  481. *
  482. * becomes:
  483. *
  484. * Fred, Bill, Joe, Jimmy
  485. *
  486. * @access public
  487. * @param string
  488. * @param string the character you wish to reduce
  489. * @param bool TRUE/FALSE - whether to trim the character from the beginning/end
  490. * @return string
  491. */
  492. public function reduce_multiples($str, $character = ',', $trim = false) {
  493. $str = preg_replace('#' . preg_quote($character, '#') . '{2,}#', $character, $str);
  494. if ($trim === true) {
  495. $str = trim($str, $character);
  496. }
  497. return $str;
  498. }
  499. }
  500. /*
  501. //explode string, return word and number of repeation
  502. $r = explode('[spilit]', $value);
  503. //regex
  504. if ( preg_match('/([a-z]+)/', $r[0])) {
  505. preg_match_all( '/'. $r[0] .'/', $this -> checkString[$arrays], $match);
  506. } else {
  507. preg_match_all( '/\\'. $r[0] .'/', $this -> checkString[$arrays], $match);
  508. }
  509. //count chars
  510. if ( count($match[0]) <= $r[1]) {
  511. $this -> _is_valid[$arrays][$valData] = true;
  512. } else {
  513. $this -> _is_valid[$arrays][$valData] = false;
  514. //set errors array
  515. $this -> error[$arrays][] = $r[0] . $this -> error_max_time_char;
  516. }
  517. */