Text.php 9.1 KB

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