TextLib.php 15 KB

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