TextLib.php 16 KB

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