TextLib.php 8.8 KB

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