TextLib.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 = null) {
  12. $this->text = $text;
  13. }
  14. /**
  15. * Count words in a text.
  16. *
  17. * //TODO use str_word_count() instead!!!
  18. *
  19. * @param string $text
  20. * @return int
  21. * 2009-11-11 ms
  22. */
  23. public static function numberOfWords($text) {
  24. $count = 0;
  25. $words = explode(' ', $text);
  26. foreach ($words as $word) {
  27. $word = trim($word);
  28. if (!empty($word)) {
  29. $count++;
  30. }
  31. }
  32. return $count;
  33. }
  34. /**
  35. * Return an abbreviated string, with characters in the middle of the
  36. * excessively long string replaced by $ending.
  37. *
  38. * @param string $text The original string.
  39. * @param integer $length The length at which to abbreviate.
  40. * @return string The abbreviated string, if longer than $length.
  41. */
  42. public static function abbreviate($text, $length = 20, $ending = '...') {
  43. return (mb_strlen($text) > $length)
  44. ? rtrim(mb_substr($text, 0, round(($length - 3) / 2))) . $ending . ltrim(mb_substr($text, (($length - 3) / 2) * -1))
  45. : $text;
  46. }
  47. /* other */
  48. public function convertToOrd($str = null, $separator = '-') {
  49. /*
  50. if (!class_exists('UnicodeLib')) {
  51. App::uses('UnicodeLib', 'Tools.Lib');
  52. }
  53. */
  54. if ($str === null) {
  55. $str = $this->text;
  56. }
  57. $chars = preg_split('//', $str, -1);
  58. $res = array();
  59. foreach ($chars as $char) {
  60. //$res[] = UnicodeLib::ord($char);
  61. $res[] = ord($char);
  62. }
  63. return implode($separator, $res);
  64. }
  65. public static function convertToOrdTable($str, $maxCols = 20) {
  66. $res = '<table>';
  67. $r = array('chr'=>array(), 'ord'=>array());
  68. $chars = preg_split('//', $str, -1);
  69. $count = 0;
  70. foreach ($chars as $key => $char) {
  71. if ($maxCols && $maxCols < $count || $key === count($chars)-1) {
  72. $res .= '<tr><th>'.implode('</th><th>', $r['chr']).'</th>';
  73. $res .= '</tr>';
  74. $res .= '<tr>';
  75. $res .= '<td>'.implode('</th><th>', $r['ord']).'</td></tr>';
  76. $count = 0;
  77. $r = array('chr'=>array(), 'ord'=>array());
  78. }
  79. $count++;
  80. //$res[] = UnicodeLib::ord($char);
  81. $r['ord'][] = ord($char);
  82. $r['chr'][] = $char;
  83. }
  84. $res .= '</table>';
  85. return $res;
  86. }
  87. /**
  88. * Explode a string of given tags into an array.
  89. */
  90. public function explodeTags($tags) {
  91. // This regexp allows the following types of user input:
  92. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  93. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  94. preg_match_all($regexp, $tags, $matches);
  95. $typed_tags = array_unique($matches[1]);
  96. $tags = array();
  97. foreach ($typed_tags as $tag) {
  98. // If a user has escaped a term (to demonstrate that it is a group,
  99. // or includes a comma or quote character), we remove the escape
  100. // formatting so to save the term into the database as the user intends.
  101. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  102. if ($tag) {
  103. $tags[] = $tag;
  104. }
  105. }
  106. return $tags;
  107. }
  108. /**
  109. * Implode an array of tags into a string.
  110. */
  111. public function implodeTags($tags) {
  112. $encoded_tags = array();
  113. foreach ($tags as $tag) {
  114. // Commas and quotes in tag names are special cases, so encode them.
  115. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  116. $tag = '"'. str_replace('"', '""', $tag) .'"';
  117. }
  118. $encoded_tags[] = $tag;
  119. }
  120. return implode(', ', $encoded_tags);
  121. }
  122. /**
  123. * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin)
  124. * by inserting a non-breaking space between the last two words.
  125. *
  126. * echo Text::widont($text);
  127. *
  128. * @param string text to remove widows from
  129. * @return string
  130. */
  131. public function widont($str = null) {
  132. if ($str === null) {
  133. $str = $this->text;
  134. }
  135. $str = rtrim($str);
  136. $space = strrpos($str, ' ');
  137. if ($space !== FALSE) {
  138. $str = substr($str, 0, $space).'&nbsp;'.substr($str, $space + 1);
  139. }
  140. return $str;
  141. }
  142. /* text object specific */
  143. /**
  144. * @param options
  145. * - min_char, max_char, case_sensititive, ...
  146. * 2010-10-09 ms
  147. */
  148. public function words($options = array()) {
  149. if (true || !$this->xr_word) {
  150. $text = str_replace(array(PHP_EOL, NL, TB), ' ', $this->text);
  151. $pieces = explode(' ', $text);
  152. $pieces = array_unique($pieces);
  153. # strip chars like . or ,
  154. foreach ($pieces as $key => $piece) {
  155. if (empty($options['case_sensitive'])) {
  156. $piece = mb_strtolower($piece);
  157. }
  158. $search = array(',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '"', '!', '?', '<', '>', '=', '/');
  159. $search = array_merge($search, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
  160. $piece = str_replace($search, '', $piece);
  161. $piece = trim($piece);
  162. if (empty($piece) || !empty($options['min_char']) && mb_strlen($piece) < $options['min_char'] || !empty($options['max_char']) && mb_strlen($piece) > $options['max_char']) {
  163. unset($pieces[$key]);
  164. } else {
  165. $pieces[$key] = $piece;
  166. }
  167. }
  168. $pieces = array_unique($pieces);
  169. //$this->xr_word = $pieces;
  170. }
  171. return $pieces;
  172. }
  173. /**
  174. * Limit the number of words in a string.
  175. *
  176. * <code>
  177. * // Returns "This is a..."
  178. * echo TextExt::maxWords('This is a sentence.', 3);
  179. *
  180. * // Limit the number of words and append a custom ending
  181. * echo Str::words('This is a sentence.', 3, '---');
  182. * </code>
  183. *
  184. * @param string $value
  185. * @param int $words
  186. * @param array $options
  187. * - ellipsis
  188. * - html
  189. * @return string
  190. */
  191. public static function maxWords($value, $words = 100, $options = array()) {
  192. $default = array(
  193. 'ellipsis' => '...'
  194. );
  195. if (!empty($options['html']) && Configure::read('App.encoding') === 'UTF-8') {
  196. $default['ellipsis'] = "\xe2\x80\xa6";
  197. }
  198. $options = array_merge($default, $options);
  199. if (trim($value) === '') {
  200. return '';
  201. }
  202. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  203. $end = $options['ellipsis'];
  204. if (mb_strlen($value) === mb_strlen($matches[0])) {
  205. $end = '';
  206. }
  207. return rtrim($matches[0]) . $end;
  208. }
  209. /**
  210. * High ASCII to Entities
  211. *
  212. * Converts High ascii text and MS Word special characters to character entities
  213. *
  214. * @access public
  215. * @param string
  216. * @return string
  217. */
  218. public function ascii_to_entities($str) {
  219. $count = 1;
  220. $out = '';
  221. $temp = array();
  222. for ($i = 0, $s = strlen($str); $i < $s; $i++) {
  223. $ordinal = ord($str[$i]);
  224. if ($ordinal < 128) {
  225. /*
  226. If the $temp array has a value but we have moved on, then it seems only
  227. fair that we output that entity and restart $temp before continuing. -Paul
  228. */
  229. if (count($temp) == 1) {
  230. $out .= '&#' . array_shift($temp) . ';';
  231. $count = 1;
  232. }
  233. $out .= $str[$i];
  234. } else {
  235. if (count($temp) == 0) {
  236. $count = ($ordinal < 224) ? 2 : 3;
  237. }
  238. $temp[] = $ordinal;
  239. if (count($temp) == $count) {
  240. $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] %
  241. 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
  242. $out .= '&#' . $number . ';';
  243. $count = 1;
  244. $temp = array();
  245. }
  246. }
  247. }
  248. return $out;
  249. }
  250. // ------------------------------------------------------------------------
  251. /**
  252. * Entities to ASCII
  253. *
  254. * Converts character entities back to ASCII
  255. *
  256. * @access public
  257. * @param string
  258. * @param bool
  259. * @return string
  260. */
  261. public function entities_to_ascii($str, $all = true) {
  262. if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) {
  263. for ($i = 0, $s = count($matches['0']); $i < $s; $i++) {
  264. $digits = $matches['1'][$i];
  265. $out = '';
  266. if ($digits < 128) {
  267. $out .= chr($digits);
  268. } elseif ($digits < 2048) {
  269. $out .= chr(192 + (($digits - ($digits % 64)) / 64));
  270. $out .= chr(128 + ($digits % 64));
  271. } else {
  272. $out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
  273. $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
  274. $out .= chr(128 + ($digits % 64));
  275. }
  276. $str = str_replace($matches['0'][$i], $out, $str);
  277. }
  278. }
  279. if ($all) {
  280. $str = str_replace(array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"),
  281. array("&", "<", ">", "\"", "'", "-"), $str);
  282. }
  283. return $str;
  284. }
  285. /**
  286. * Reduce Double Slashes
  287. *
  288. * Converts double slashes in a string to a single slash,
  289. * except those found in http://
  290. *
  291. * http://www.some-site.com//index.php
  292. *
  293. * becomes:
  294. *
  295. * http://www.some-site.com/index.php
  296. *
  297. * @access public
  298. * @param string
  299. * @return string
  300. */
  301. public function reduce_double_slashes($str) {
  302. return preg_replace("#([^:])//+#", "\\1/", $str);
  303. }
  304. // ------------------------------------------------------------------------
  305. /**
  306. * Reduce Multiples
  307. *
  308. * Reduces multiple instances of a particular character. Example:
  309. *
  310. * Fred, Bill,, Joe, Jimmy
  311. *
  312. * becomes:
  313. *
  314. * Fred, Bill, Joe, Jimmy
  315. *
  316. * @access public
  317. * @param string
  318. * @param string the character you wish to reduce
  319. * @param bool TRUE/FALSE - whether to trim the character from the beginning/end
  320. * @return string
  321. */
  322. public function reduce_multiples($str, $character = ',', $trim = false) {
  323. $str = preg_replace('#' . preg_quote($character, '#') . '{2,}#', $character, $str);
  324. if ($trim === true) {
  325. $str = trim($str, $character);
  326. }
  327. return $str;
  328. }
  329. }