Text.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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<string, mixed> $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. /** @var array<string> $chars */
  148. $chars = preg_split('//', $str, -1);
  149. $res = [];
  150. foreach ($chars as $char) {
  151. //$res[] = UnicodeLib::ord($char);
  152. $res[] = ord($char);
  153. }
  154. return implode($separator, $res);
  155. }
  156. /**
  157. * Explode a string of given tags into an array.
  158. *
  159. * @param string $tags
  160. * @return array<string>
  161. */
  162. public function explodeTags($tags) {
  163. // This regexp allows the following types of user input:
  164. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  165. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  166. preg_match_all($regexp, $tags, $matches);
  167. $typedTags = array_unique($matches[1]);
  168. $tags = [];
  169. foreach ($typedTags as $tag) {
  170. // If a user has escaped a term (to demonstrate that it is a group,
  171. // or includes a comma or quote character), we remove the escape
  172. // formatting so to save the term into the database as the user intends.
  173. /** @var string $replacedString */
  174. $replacedString = str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag));
  175. $tag = trim($replacedString);
  176. if ($tag) {
  177. $tags[] = $tag;
  178. }
  179. }
  180. return $tags;
  181. }
  182. /**
  183. * Implode an array of tags into a string.
  184. *
  185. * @param array<string> $tags
  186. * @return string
  187. */
  188. public function implodeTags(array $tags) {
  189. $encodedTags = [];
  190. foreach ($tags as $tag) {
  191. // Commas and quotes in tag names are special cases, so encode them.
  192. if (strpos($tag, ',') !== false || strpos($tag, '"') !== false) {
  193. $tag = '"' . str_replace('"', '""', $tag) . '"';
  194. }
  195. $encodedTags[] = $tag;
  196. }
  197. return implode(', ', $encodedTags);
  198. }
  199. /**
  200. * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin)
  201. * by inserting a non-breaking space between the last two words.
  202. *
  203. * echo Text::widont($text);
  204. *
  205. * @param string $str Text to remove widows from
  206. * @return string
  207. */
  208. public function widont($str) {
  209. $str = rtrim($str);
  210. $space = strrpos($str, ' ');
  211. if ($space !== false) {
  212. $str = substr($str, 0, $space) . '&nbsp;' . substr($str, $space + 1);
  213. }
  214. return $str;
  215. }
  216. /**
  217. * Extract words
  218. *
  219. * @param string $text
  220. * @param array<string, mixed> $options
  221. * - min_char, max_char, case_sensititive, ...
  222. * @return array<string>
  223. */
  224. public function words($text, array $options = []) {
  225. $text = str_replace([PHP_EOL, "\t"], ' ', $text);
  226. $pieces = explode(' ', $text);
  227. $pieces = array_unique($pieces);
  228. // strip chars like . or ,
  229. foreach ($pieces as $key => $piece) {
  230. if (empty($options['case_sensitive'])) {
  231. $piece = mb_strtolower($piece);
  232. }
  233. $search = [',', '.', ';', ':', '#', '', '(', ')', '{', '}', '[', ']', '$', '%', '"', '!', '?', '<', '>', '=', '/'];
  234. $search = array_merge($search, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
  235. $piece = str_replace($search, '', $piece);
  236. $piece = trim($piece);
  237. if (empty($piece) || !empty($options['min_char']) && mb_strlen($piece) < $options['min_char'] || !empty($options['max_char']) && mb_strlen($piece) > $options['max_char']) {
  238. unset($pieces[$key]);
  239. } else {
  240. $pieces[$key] = $piece;
  241. }
  242. }
  243. $pieces = array_unique($pieces);
  244. return $pieces;
  245. }
  246. /**
  247. * Limit the number of words in a string.
  248. *
  249. * <code>
  250. * // Returns "This is a..."
  251. * echo TextExt::maxWords('This is a sentence.', 3);
  252. *
  253. * // Limit the number of words and append a custom ending
  254. * echo Str::words('This is a sentence.', 3, '---');
  255. * </code>
  256. *
  257. * @param string $value
  258. * @param int $words
  259. * @param array<string, mixed> $options
  260. * - ellipsis
  261. * - html
  262. * @return string
  263. */
  264. public static function maxWords($value, $words = 100, array $options = []) {
  265. $defaults = [
  266. 'ellipsis' => '...',
  267. ];
  268. if (!empty($options['html']) && Configure::read('App.encoding') === 'UTF-8') {
  269. $defaults['ellipsis'] = "\xe2\x80\xa6";
  270. }
  271. $options += $defaults;
  272. if (trim($value) === '') {
  273. return '';
  274. }
  275. preg_match('/^\s*+(?:\S++\s*+){1,' . $words . '}/u', $value, $matches);
  276. $end = $options['ellipsis'];
  277. if (mb_strlen($value) === mb_strlen($matches[0])) {
  278. $end = '';
  279. }
  280. return rtrim($matches[0]) . $end;
  281. }
  282. /**
  283. * High ASCII to Entities
  284. *
  285. * Converts High ascii text and MS Word special characters to character entities
  286. *
  287. * @param string $str
  288. * @return string
  289. */
  290. public function asciiToEntities($str) {
  291. $count = 1;
  292. $out = '';
  293. $temp = [];
  294. for ($i = 0, $s = strlen($str); $i < $s; $i++) {
  295. $ordinal = ord($str[$i]);
  296. if ($ordinal < 128) {
  297. /*
  298. If the $temp array has a value but we have moved on, then it seems only
  299. fair that we output that entity and restart $temp before continuing. -Paul
  300. */
  301. if (count($temp) == 1) {
  302. $out .= '&#' . array_shift($temp) . ';';
  303. $count = 1;
  304. }
  305. $out .= $str[$i];
  306. } else {
  307. if (count($temp) == 0) {
  308. $count = ($ordinal < 224) ? 2 : 3;
  309. }
  310. $temp[] = $ordinal;
  311. if (count($temp) == $count) {
  312. $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] %
  313. 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
  314. $out .= '&#' . $number . ';';
  315. $count = 1;
  316. $temp = [];
  317. }
  318. }
  319. }
  320. return $out;
  321. }
  322. /**
  323. * Entities to ASCII
  324. *
  325. * Converts character entities back to ASCII
  326. *
  327. * @param string $str
  328. * @param bool $all
  329. * @return string
  330. */
  331. public function entitiesToAscii($str, $all = true) {
  332. if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) {
  333. for ($i = 0, $s = count($matches['0']); $i < $s; $i++) {
  334. $digits = $matches['1'][$i];
  335. $out = '';
  336. if ($digits < 128) {
  337. $out .= chr($digits);
  338. } elseif ($digits < 2048) {
  339. $out .= chr(192 + (int)(($digits - ($digits % 64)) / 64));
  340. $out .= chr(128 + ($digits % 64));
  341. } else {
  342. $out .= chr(224 + (int)(($digits - ($digits % 4096)) / 4096));
  343. $out .= chr(128 + (int)((($digits % 4096) - ($digits % 64)) / 64));
  344. $out .= chr(128 + ($digits % 64));
  345. }
  346. $str = str_replace($matches['0'][$i], $out, $str);
  347. }
  348. }
  349. if ($all) {
  350. $str = str_replace(
  351. ['&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#45;'],
  352. ['&', '<', '>', '"', "'", '-'],
  353. $str,
  354. );
  355. }
  356. return $str;
  357. }
  358. /**
  359. * Reduce Double Slashes
  360. *
  361. * Converts double slashes in a string to a single slash,
  362. * except those found in http://
  363. *
  364. * http://www.some-site.com//index.php
  365. *
  366. * becomes:
  367. *
  368. * http://www.some-site.com/index.php
  369. *
  370. * @param string $str
  371. * @return string
  372. */
  373. public function reduceDoubleSlashes($str) {
  374. return preg_replace('#([^:])//+#', '\\1/', $str);
  375. }
  376. }