PageRenderTime 29ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/Strings.class.php

https://gitlab.com/karl3/gs_libs
PHP | 1781 lines | 888 code | 215 blank | 678 comment | 174 complexity | e6815fcd8175d80fd1143a5c77dbc3cf MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. * A PHP library of helpful string manipulation methods. This class does
  5. * not need to be assigned to an object, as you could use the :: access method,
  6. * such as Strings::isString to access them statically
  7. */
  8. class Strings
  9. {
  10. /**
  11. * Validates whether the given element is a string.
  12. *
  13. * @return bool
  14. *
  15. * @param string $element
  16. * @param bool $require_content If the string can be empty or not
  17. */
  18. public static function isString($element, $require_content = true)
  19. {
  20. return (!is_string($element)) ? false : ($require_content && $element == '' ? false : true);
  21. }
  22. /**
  23. * Converts all strings, or all elements of an array, no matter how nested
  24. * the array is, to html entities.
  25. *
  26. * @return string|array
  27. *
  28. * @param string|array $element
  29. */
  30. public static function convertTextToHTML($element)
  31. {
  32. return Strings::processFunction($element, 'htmlentities');
  33. }
  34. /**
  35. * Removes the first or last word from a string.
  36. *
  37. * @return string
  38. *
  39. * @param string $string
  40. * @param bool $start whether to trim at start (true) or end (false) of string
  41. */
  42. public static function trimWordFromString($string, $start = true)
  43. {
  44. if (Strings::isString($string)) {
  45. $trimmed = trim($string);
  46. if (!substr_count($trimmed, ' ')) {
  47. return $trimmed;
  48. } else {
  49. return ($start) ? substr($trimmed, strpos($trimmed, ' ') + 1, strlen($trimmed)) : substr($trimmed, 0, strrpos($trimmed, ' '));
  50. }
  51. }
  52. return false;
  53. }
  54. /**
  55. * Removes the first word from a string.
  56. *
  57. * @return string
  58. *
  59. * @param string $string
  60. *
  61. * @see trimWordFromString()
  62. */
  63. public static function trimFirstWordFromString($string)
  64. {
  65. return Strings::trimWordFromString($string, true);
  66. }
  67. /**
  68. * Removes the last word from a string.
  69. *
  70. * @return string
  71. *
  72. * @param string $string
  73. *
  74. * @see trimWordFromString()
  75. */
  76. public static function trimLastWordFromString($string)
  77. {
  78. return Strings::trimWordFromString($string, false);
  79. }
  80. /**
  81. * @param $string
  82. *
  83. * @return array|bool|string
  84. */
  85. public static function trimString($string)
  86. {
  87. if (Strings::isString($string)) {
  88. return Strings::processFunction($string, 'trim');
  89. }
  90. return false;
  91. }
  92. /**
  93. * Can left-trim a string, or all elements of an array, no matter
  94. * how nested the array is.
  95. *
  96. * @param $string
  97. *
  98. * @return array|bool|string
  99. */
  100. public static function trimStringLeft($string)
  101. {
  102. if (Strings::isString($string)) {
  103. return Strings::processFunction($string, 'ltrim');
  104. }
  105. return false;
  106. }
  107. /**
  108. * Can right-trim a string, or all elements of an array, no matter
  109. * how nested the array is.
  110. *
  111. * @param $string
  112. *
  113. * @return array|bool|string
  114. */
  115. public static function trimStringRight($string)
  116. {
  117. if (Strings::isString($string)) {
  118. return Strings::processFunction($string, 'rtrim');
  119. }
  120. return false;
  121. }
  122. /**
  123. * Adds slashes to a string, or all elements of an array, no matter
  124. * how nested the array is.
  125. *
  126. * If the 'check_gpc' parameter is true then slashes will be applied
  127. * depending on magic_quotes setting.
  128. *
  129. * @return string|array
  130. *
  131. * @param string|array $element
  132. * @param bool $check_gpc
  133. */
  134. public static function addSlashesToString($element, $check_gpc = true)
  135. {
  136. return ($check_gpc && get_magic_quotes_gpc()) ? $element : Strings::processFunction($element, 'addslashes');
  137. }
  138. /**
  139. * Removes slashes from a string, or all elements of an array, no matter
  140. * how nested the array is.
  141. *
  142. * If the 'check_gpc' parameter is true then slashes will be removed
  143. * depending on magic_quotes setting.
  144. *
  145. * @return string|array
  146. *
  147. * @param string|array $element
  148. * @param bool $check_gpc
  149. */
  150. public static function trimSlashesFromString($element, $check_gpc = true)
  151. {
  152. return ($check_gpc && !get_magic_quotes_gpc()) ? $element : Strings::processFunction($element, 'stripslashes');
  153. }
  154. /**
  155. * Performs the passed function recursively.
  156. *
  157. * @return string|array
  158. *
  159. * @param string|array $element
  160. * @param string $function
  161. */
  162. public static function processFunction($element, $function)
  163. {
  164. if (function_exists($function) === true) {
  165. return $function($element);
  166. }
  167. return false;
  168. }
  169. /**
  170. * Get the ordinal value of a number (1st, 2nd, 3rd, 4th).
  171. *
  172. * @return string
  173. *
  174. * @param int $value
  175. */
  176. public static function getOrdinalString($value)
  177. {
  178. static $ords = array('th', 'st', 'nd', 'rd');
  179. if ((($value %= 100) > 9 && $value < 20) || ($value %= 10) > 3) {
  180. $value = 0;
  181. }
  182. return $ords[$value];
  183. }
  184. /**
  185. * Returns the plural appendage, handy for instances like: 1 file,
  186. * 5 files, 1 box, 3 boxes.
  187. *
  188. * @return string
  189. *
  190. * @param int $value
  191. * @param string $append what value to append to the string
  192. */
  193. public static function getPluralString($value, $append = 's')
  194. {
  195. return ($value == 1 ? '' : $append);
  196. }
  197. /**
  198. * @param $word
  199. *
  200. * @return bool|mixed
  201. */
  202. public static function pluralize($word)
  203. {
  204. $plural = array(
  205. '/(quiz)$/i' => '1zes',
  206. '/^(ox)$/i' => '1en',
  207. '/([m|l])ouse$/i' => '1ice',
  208. '/(matr|vert|ind)ix|ex$/i' => '1ices',
  209. '/(x|ch|ss|sh)$/i' => '1es',
  210. '/([^aeiouy]|qu)ies$/i' => '1y',
  211. '/([^aeiouy]|qu)y$/i' => '1ies',
  212. '/(hive)$/i' => '1s',
  213. '/(?:([^f])fe|([lr])f)$/i' => '12ves',
  214. '/sis$/i' => 'ses',
  215. '/([ti])um$/i' => '1a',
  216. '/(buffal|tomat)o$/i' => '1oes',
  217. '/(bu)s$/i' => '1ses',
  218. '/(alias|status)/i' => '1es',
  219. '/(octop|vir)us$/i' => '1i',
  220. '/(ax|test)is$/i' => '1es',
  221. '/s$/i' => 's',
  222. '/$/' => 's');
  223. $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
  224. $irregular = array(
  225. 'person' => 'people',
  226. 'man' => 'men',
  227. 'child' => 'children',
  228. 'sex' => 'sexes',
  229. 'move' => 'moves');
  230. $lowercased_word = strtolower($word);
  231. foreach ($uncountable as $_uncountable) {
  232. if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
  233. return $word;
  234. }
  235. }
  236. foreach ($irregular as $_plural => $_singular) {
  237. if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
  238. return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
  239. }
  240. }
  241. foreach ($plural as $rule => $replacement) {
  242. if (preg_match($rule, $word)) {
  243. return preg_replace($rule, $replacement, $word);
  244. }
  245. }
  246. return false;
  247. }
  248. /**
  249. * Strips all newline characters (\n) from a string
  250. *
  251. * @return string
  252. *
  253. * @param string
  254. */
  255. public static function trimNewlinesFromString($string)
  256. {
  257. if (Strings::isString($string)) {
  258. return str_replace("\n", '', $string);
  259. }
  260. return false;
  261. }
  262. /**
  263. * Strips all carriage return characters (\r) from a string
  264. *
  265. * @param $string
  266. *
  267. * @return string
  268. */
  269. public static function trimCarriageReturnsFromString($string)
  270. {
  271. if (Strings::isString($string)) {
  272. return str_replace("\r", '', $string);
  273. }
  274. return false;
  275. }
  276. /**
  277. * Counts number of words in a string.
  278. *
  279. * if $real_words == true then remove things like '-', '+', that
  280. * are surrounded with white space.
  281. *
  282. * @return string|null
  283. *
  284. * @param string $string
  285. * @param bool $real_words
  286. */
  287. public static function countWords($string, $real_words = true)
  288. {
  289. if (Strings::isString($string)) {
  290. if ($real_words == true) {
  291. $string = preg_replace('/(\s+)[^a-zA-Z0-9](\s+)/', ' ', $string);
  292. }
  293. return (count(split('[[:space:]]+', $string)));
  294. }
  295. return false;
  296. }
  297. /**
  298. * Counts number of sentences in a string.
  299. *
  300. * @return string|null
  301. *
  302. * @param string $string
  303. */
  304. public static function countSentences($string)
  305. {
  306. if (Strings::isString($string)) {
  307. return preg_match_all('/[^\s]\.(?!\w)/', $string, $matches);
  308. }
  309. return false;
  310. }
  311. /**
  312. * Counts number of paragraphs in a string.
  313. *
  314. * @return string|null
  315. *
  316. * @param string $string
  317. */
  318. public static function countParagraphs($string)
  319. {
  320. if (Strings::isString($string)) {
  321. $string = str_replace("\r", "\n", $string);
  322. return count(preg_split('/[\n]+/', $string));
  323. }
  324. return false;
  325. }
  326. /**
  327. *
  328. * @param string $string
  329. *
  330. * @return int
  331. */
  332. public static function countLines($string)
  333. {
  334. if (Strings::isString($string)) {
  335. $array = explode("\n", $string);
  336. $array = Arrays::arrayRemoveEmpty($array);
  337. return count($array);
  338. }
  339. return false;
  340. }
  341. /**
  342. * Gather information about a passed string.
  343. *
  344. * If $real_words == true then remove things like '-', '+', that are
  345. * surrounded with white space.
  346. *
  347. * @return string|null
  348. *
  349. * @param string $string
  350. * @param bool $real_words
  351. */
  352. public static function getStringInformation($string, $real_words = true)
  353. {
  354. if (Strings::isString($string)) {
  355. $info = array();
  356. $info['character'] = ($real_words) ? preg_match_all('/[^\s]/', $string, $matches) : strlen($string);
  357. $info['word'] = Strings::countWords($string, $real_words);
  358. $info['sentence'] = Strings::countSentences($string);
  359. $info['paragraph'] = Strings::countParagraphs($string);
  360. return $info;
  361. }
  362. return false;
  363. }
  364. /**
  365. *
  366. * @desc abusive language filter, replaces bad words in a string with '****'
  367. *
  368. * @param string $string string of text
  369. * @param array $swear the array of swear words to eliminate
  370. *
  371. * @return string the same input string is redisplayed with the curse words removed
  372. */
  373. public function abusiveLanguage($string, $swear)
  374. {
  375. if (Strings::isString($string)) {
  376. foreach ($swear as $value) {
  377. $string = str_replace($value, "****", $string);
  378. }
  379. return $string;
  380. }
  381. return false;
  382. }
  383. /**
  384. *
  385. * formats plain text to be more readable
  386. *
  387. * @param string $string string of text
  388. * @param bool $add_links
  389. *
  390. * @return string the same input string is redisplayed with new formatting
  391. */
  392. public static function plainTextDisplay($string, $add_links = true)
  393. {
  394. if (Strings::isString($string)) {
  395. $string = strip_tags($string);
  396. // strip out HTML
  397. $string = nl2br($string); // add break tags in place of new lines
  398. if ($add_links == true) {
  399. $string = HTML::addLinks($string); // add links where needed
  400. $string = HTML::email_links($string); // add e-mail addresses where needed
  401. }
  402. return $string;
  403. }
  404. return false;
  405. }
  406. /**
  407. * @param $codes
  408. *
  409. * @return string
  410. */
  411. public static function uchr($codes)
  412. {
  413. if (is_scalar($codes))
  414. $codes = func_get_args();
  415. $str = '';
  416. foreach ($codes as $code)
  417. $str .= html_entity_decode('&#' . $code . ';', ENT_NOQUOTES, 'UTF-8');
  418. return $str;
  419. }
  420. /**
  421. *
  422. * function will encrypt text. Used on passwords both functions for encrypt and decrypt found elsewhere
  423. * props to whoever wrote these (I forgot, sorry)
  424. *
  425. * @param string $string the string of text to be encrypted
  426. * @param string $key the encryption key
  427. *
  428. * @return string the input string is redisplayed in an encrypted form
  429. */
  430. public static function uEnCrypt($string, $key)
  431. {
  432. if (Strings::isString($string)) {
  433. $in = iconv_get_encoding("input_encoding");
  434. $string = iconv($in, 'UTF-8', $string);
  435. $result = '';
  436. for ($i = 1; $i <= strlen($string); $i++) {
  437. $char = substr($string, $i - 1, 1);
  438. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  439. $char = Strings::uchr(ord($char) + ord($keychar));
  440. $result .= $char;
  441. }
  442. return $result;
  443. }
  444. return false;
  445. }
  446. /**
  447. *
  448. * function will decrypt text that has been encrypted with the above function
  449. * must be decrypted using the same $key as the one used to encrypt it
  450. *
  451. * @param string $string the string of text to be decrypted
  452. * @param string $key the encryption key
  453. *
  454. * @return string the input string (which has been ENcrypted using the function above
  455. * is redisplayed in DEcrypted format
  456. */
  457. public static function uDeCrypt($string, $key)
  458. {
  459. if (Strings::isString($string)) {
  460. $result = '';
  461. for ($i = 1; $i <= strlen($string); $i++) {
  462. $char = substr($string, $i - 1, 1);
  463. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  464. $char = Strings::uchr(ord($char) - ord($keychar));
  465. $result .= $char;
  466. }
  467. return $result;
  468. }
  469. return false;
  470. }
  471. /**
  472. *
  473. * function will encrypt text. Used on passwords both functions for encrypt and decrypt found elsewhere
  474. * props to whoever wrote these (I forgot, sorry)
  475. *
  476. * @param string $string the string of text to be encrypted
  477. * @param string $key the encryption key
  478. *
  479. * @return string the input string is redisplayed in an encrypted form
  480. */
  481. public static function enCrypt($string, $key)
  482. {
  483. if (Strings::isString($string)) {
  484. $result = '';
  485. for ($i = 1; $i <= strlen($string); $i++) {
  486. $char = substr($string, $i - 1, 1);
  487. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  488. $char = chr(ord($char) + ord($keychar));
  489. $result .= $char;
  490. }
  491. return $result;
  492. }
  493. return false;
  494. }
  495. /**
  496. *
  497. * function will decrypt text that has been encrypted with the above function
  498. * must be decrypted using the same $key as the one used to encrypt it
  499. *
  500. * @param string $string the string of text to be decrypted
  501. * @param string $key the encryption key
  502. *
  503. * @return string the input string (which has been ENcrypted using the function above
  504. * is redisplayed in DEcrypted format
  505. */
  506. public static function deCrypt($string, $key)
  507. {
  508. if (Strings::isString($string)) {
  509. $result = '';
  510. for ($i = 1; $i <= strlen($string); $i++) {
  511. $char = substr($string, $i - 1, 1);
  512. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  513. $char = chr(ord($char) - ord($keychar));
  514. $result .= $char;
  515. }
  516. return $result;
  517. }
  518. return false;
  519. }
  520. /**
  521. *
  522. * function to generate random strings
  523. *
  524. * @param int $length number of characters in the generated string
  525. *
  526. * @return string a new string is created with random characters of the desired length
  527. */
  528. public static function randomString($length = 32)
  529. {
  530. $randstr = '';
  531. srand((double)microtime(true) * 1000000);
  532. //our array add all letters and numbers if you wish
  533. $chars = array(
  534. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p',
  535. 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5',
  536. '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  537. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
  538. for ($rand = 0; $rand <= $length; $rand++) {
  539. $random = rand(0, count($chars) - 1);
  540. $randstr .= $chars[$random];
  541. }
  542. return $randstr;
  543. }
  544. /**
  545. * Generates a BLOWFISH encrypted string
  546. *
  547. * @Todo test this. May not be working
  548. *
  549. * @param $string
  550. *
  551. * @return string
  552. */
  553. public static function bCrypt($string)
  554. {
  555. if (Strings::isString($string)) {
  556. return crypt($string, '$2a$16$' . Strings::randomString(22));
  557. }
  558. return false;
  559. }
  560. /**
  561. *
  562. * takes a string of text and obfuscates all but the last 4 digits.
  563. * perfect for credit cards and SSNs
  564. *
  565. * @param string $string the string of text being obfuscated
  566. *
  567. * @return string
  568. */
  569. public static function obfuscateString($string)
  570. {
  571. if (Strings::isString($string)) {
  572. return str_pad(substr($string, -4), strlen($string), 'x', STR_PAD_LEFT);
  573. }
  574. return false;
  575. }
  576. /**
  577. *
  578. * takes two names and concatenates it as
  579. * first letter of the first name, full last name
  580. * such as 'kgroves' out of "Karl" and "Groves"
  581. *
  582. * @param $first
  583. * @param $last
  584. *
  585. * @return string
  586. */
  587. public static function concatString($first, $last)
  588. {
  589. $first = strtoupper($first);
  590. $first = strtolower($first);
  591. $first_initial = $first{0};
  592. $last = strtoupper($last);
  593. $last = strtolower($last);
  594. $concat = $first_initial;
  595. $concat .= $last;
  596. return $concat;
  597. }
  598. /**
  599. *
  600. * makes a long string of text shorter
  601. *
  602. * @param string $string the text being shortened
  603. * @param int $length the length of the new string
  604. * @param bool $use_title whether or not to put the full text in a title attribute
  605. * @param string $class what class to apply
  606. *
  607. * @return string the shortened string of text
  608. */
  609. public static function truncateString($string, $length, $use_title = false, $class = '')
  610. {
  611. if (Strings::isString($string)) {
  612. $output = '';
  613. if (strlen($string) > $length) {
  614. $output .= substr($string, 0, $length);
  615. $output .= "...";
  616. if ($use_title == true) {
  617. $output = "<span title=\"$string\" $class>$output</span>";
  618. }
  619. } else {
  620. $output = $string;
  621. }
  622. return $output;
  623. }
  624. return false;
  625. }
  626. /**
  627. *
  628. * does a fancy truncate on a link so it doesn't b0rk anything
  629. * i.e. http://www.example.com/reallylonglinkishere.html
  630. * becomes something like
  631. * http://www.example.com/r...here.html
  632. *
  633. * @param string $link the link
  634. * @param int $limit the number of characters allowed
  635. *
  636. * @return string the same input string is returned, shortened
  637. */
  638. public static function trimLink($link, $limit = 50)
  639. {
  640. if ($limit > 39) {
  641. // we test the limit that it's at least 39 characters,
  642. // otherwise our presentation will look awkward!
  643. //// figure out the total length of the link title
  644. if (strlen($link) > $limit) {
  645. // edit the link
  646. // we also return the last 10 characters of the long
  647. // URL i.e. the '-10' value in the line below
  648. $link = substr($link, 0, ($limit / 2)) . '...' .
  649. substr($link, -10);
  650. }
  651. }
  652. // return the processed string
  653. return $link;
  654. }
  655. /**
  656. * similar to above but preferred due to robustness
  657. *
  658. * @param string $string the string to truncate
  659. * @param int $maxLength the maximum final length of the string
  660. * @param string $separator the separator in the middle of the truncated string
  661. *
  662. * @return string
  663. */
  664. public static function truncateToMiddle($string, $maxLength, $separator = '/.../')
  665. {
  666. if (Strings::isString($string)) {
  667. $separatorLength = strlen($separator);
  668. $maxLength = $maxLength - $separatorLength;
  669. $start = $maxLength / 2;
  670. $trunc = strlen($string) - $maxLength;
  671. return substr_replace($string, $separator, $start, $trunc);
  672. }
  673. return false;
  674. }
  675. /**
  676. *
  677. * exactly the opposite of PHP's nl2br, this function
  678. * takes <br> elements and turns them into \n
  679. *
  680. * @param string $string the string of text to be modified
  681. *
  682. * @return string
  683. */
  684. public static function br2nl($string)
  685. {
  686. if (Strings::isString($string)) {
  687. return preg_replace('/<br\\\\s*?\\/??>/i', "\\n", $string);
  688. }
  689. return false;
  690. }
  691. /**
  692. * @name bin2text
  693. * @desc convert binary string to text
  694. *
  695. * @param string $string
  696. *
  697. * @return string the newly converted text
  698. */
  699. public static function bin2text($string)
  700. {
  701. if (Strings::isString($string)) {
  702. $text_str = '';
  703. $chars = explode("\n", chunk_split(str_replace("\n", '', $string), 8));
  704. $_I = count($chars);
  705. for ($i = 0; $i < $_I; $text_str .= chr(bindec($chars[$i])), $i++) ;
  706. return $text_str;
  707. }
  708. return false;
  709. }
  710. /**
  711. *
  712. * convert a string to binary
  713. *
  714. * @param string $string
  715. *
  716. * @return string the new binary string
  717. */
  718. public static function text2bin($string)
  719. {
  720. if (Strings::isString($string)) {
  721. $len = strlen($string);
  722. $bin = '';
  723. for ($i = 0; $i < $len; $i++) {
  724. $bin .= strlen(decbin(ord($string[$i]))) < 8 ? str_pad(decbin(ord($string[$i])), 8, 0, STR_PAD_LEFT) : decbin(ord($string[$i]));
  725. }
  726. return $bin;
  727. }
  728. return false;
  729. }
  730. /**
  731. * chop a string to maximum # of words
  732. *
  733. * @param string $str the string we're chopping
  734. * @param int $max_words number of words to return
  735. * @param string $append what to put at the end of the string
  736. *
  737. * @return string the chopped string
  738. */
  739. public static function wordChop($str, $max_words = 15, $append = "...")
  740. {
  741. if (Strings::isString($str)) {
  742. $e = explode(' ', $str);
  743. $w = count($e);
  744. if ($w > $max_words) {
  745. $str = '';
  746. for ($i = 0; $i < $max_words; $i++) {
  747. $str .= ' ' . $e[$i];
  748. }
  749. $str .= $append;
  750. }
  751. return ($str);
  752. } else {
  753. return false;
  754. }
  755. }
  756. /**
  757. *
  758. * determines whether the first letter is uppercase or not
  759. *
  760. * @param string $string the string to analyze
  761. *
  762. * @return bool
  763. */
  764. public static function isFirstLetterUpper($string)
  765. {
  766. if (Strings::isString($string)) {
  767. if (strstr($string[0], ucfirst($string[0]))) {
  768. return true;
  769. } else {
  770. return false;
  771. }
  772. } else {
  773. return false;
  774. }
  775. }
  776. /**
  777. *
  778. * determines if one string is contained in another
  779. *
  780. * @param string $str
  781. * @param string $content
  782. * @param bool $ignorecase
  783. *
  784. * @return bool
  785. */
  786. public static function contains($str, $content, $ignorecase = true)
  787. {
  788. if (Strings::isString($str)) {
  789. if ($ignorecase) {
  790. $str = strtolower($str);
  791. $content = strtolower($content);
  792. if (false === stripos($content, $str)) {
  793. return false;
  794. }
  795. }
  796. if (false === strpos($content, $str)) {
  797. return false;
  798. }
  799. return true;
  800. } else {
  801. return false;
  802. }
  803. }
  804. /**
  805. * determines if any item in an array is found within a string
  806. *
  807. * @param array $array
  808. * @param string $string
  809. *
  810. * @return bool
  811. */
  812. public static function arrayItemInString($array, $string)
  813. {
  814. if (Strings::isString($string)) {
  815. foreach ($array AS $item) {
  816. if (!stristr($string, $item) === false) {
  817. return true;
  818. }
  819. }
  820. return false;
  821. } else {
  822. return false;
  823. }
  824. }
  825. /**
  826. * takes all instances of multiple spaces and turns them into a single space
  827. *
  828. * @param string $string the string being cleaned
  829. *
  830. * @return string the cleaned string
  831. */
  832. public static function collapseWhiteSpace($string)
  833. {
  834. if (Strings::isString($string)) {
  835. return preg_replace('/\s\s+/', ' ', $string);
  836. } else {
  837. return false;
  838. }
  839. }
  840. /**
  841. * smart capitalization of words
  842. *
  843. * @param string $string the string to be capitalized
  844. *
  845. * @return string the cleaned string
  846. */
  847. public static function titleCase($string)
  848. {
  849. if (Strings::isString($string)) {
  850. // Our array of 'small words' which shouldn't be capitalised if
  851. // they aren't the first word. Add your own words to taste.
  852. $smallwordsarray = array(
  853. 'of', 'a', 'the', 'and', 'an', 'or', 'nor', 'but', 'is', 'if', 'then', 'else', 'when',
  854. 'at', 'from', 'by', 'on', 'off', 'for', 'in', 'out', 'over', 'to', 'into', 'with'
  855. );
  856. // Split the string into separate words
  857. $words = explode(' ', $string);
  858. foreach ($words as $key => $word) {
  859. // If this word is the first, or it's not one of our small words, capitalise it
  860. // with ucwords().
  861. if ($key == 0 || !in_array($word, $smallwordsarray)) {
  862. $words[$key] = ucwords(strtolower($word));
  863. }
  864. }
  865. // Join the words back into a string
  866. $newtitle = implode(' ', $words);
  867. return $newtitle;
  868. }
  869. return false;
  870. }
  871. /**
  872. * eliminates all white space from a string
  873. *
  874. * @param string $string the string being cleaned
  875. *
  876. * @return string the cleaned string
  877. */
  878. public static function stripWhiteSpace($string)
  879. {
  880. if (Strings::isString($string)) {
  881. return preg_replace('/\s+/', '', $string);
  882. } else {
  883. return false;
  884. }
  885. }
  886. /**
  887. *
  888. * removes specified words from a string
  889. *
  890. * @param string $string the string to strip words from
  891. * @param array $stopwords the array of words to strip from string
  892. * @param string $return the return type
  893. * basically if it is set to "string" it will return
  894. * a string. otherwise it will return an array
  895. *
  896. * @return mixed - based on the value of $return
  897. */
  898. public static function stripStopWords($string, $stopwords, $return = "string")
  899. {
  900. if (Strings::isString($string)) {
  901. $stopwords = array_flip($stopwords);
  902. $strarray = explode(' ', $string); // Create an array of words from the string
  903. $new_text = array(); // Create an array to hold the new string
  904. foreach ($strarray as $key => $word) {
  905. if (!array_key_exists($word, $stopwords)) {
  906. $new_text[] = $word; // If this word isn't a stopword, add it
  907. }
  908. }
  909. if ($return == "string") {
  910. return implode(' ', $new_text);
  911. } else {
  912. return $new_text;
  913. }
  914. } else {
  915. return false;
  916. }
  917. }
  918. /**
  919. * strips non alphabetical characters from a string, preserving spaces
  920. *
  921. * @param string $string string to be cleaned
  922. *
  923. * @return string
  924. */
  925. public static function stripNonAlpha($string)
  926. {
  927. if (Strings::isString($string)) {
  928. return preg_replace("/[^A-Za-z\s\s+]/", "", $string);
  929. } else {
  930. return false;
  931. }
  932. }
  933. /**
  934. * strips non alphanumeric characters from a string
  935. *
  936. * @param string $string string to be cleaned
  937. * @param bool $preserveSpaces
  938. *
  939. * @return string
  940. */
  941. public static function stripNonAlphanumeric($string, $preserveSpaces = true)
  942. {
  943. if (Strings::isString($string)) {
  944. if ($preserveSpaces == false) {
  945. return preg_replace('/[^\p{L}\p{N}\s]/u', '', $string);
  946. } else {
  947. return preg_replace("/[^A-Za-z0-9\s\s+]/", "", $string);
  948. }
  949. } else {
  950. return false;
  951. }
  952. }
  953. /**
  954. *
  955. * converts a string to a specified case, such as all upper case
  956. *
  957. * @param string $string string to be cleaned
  958. * @param string $mode the mode to use when converting the string
  959. *
  960. * @return string
  961. */
  962. public static function convertStringCase($string, $mode)
  963. {
  964. if (Strings::isString($string)) {
  965. switch ($mode) {
  966. case "upper":
  967. return strtoupper($string);
  968. case "lower":
  969. return strtolower($string);
  970. case "ucfirst":
  971. return ucfirst($string);
  972. case "lcfirst":
  973. return lcfirst($string);
  974. case "ucwords":
  975. return ucwords($string);
  976. default:
  977. return $string;
  978. }
  979. } else {
  980. return false;
  981. }
  982. }
  983. /**
  984. *
  985. * get the length of a string
  986. *
  987. * @param string $string string to be checked
  988. * @param bool $noHTML whether or not HTML should be stripped first
  989. *
  990. * @return string
  991. */
  992. public static function getStringLength($string, $noHTML = true)
  993. {
  994. if (Strings::isString($string)) {
  995. if ($noHTML == true) {
  996. strip_tags($string);
  997. }
  998. return Strings::processFunction($string, 'strlen');
  999. } else {
  1000. return false;
  1001. }
  1002. }
  1003. /**
  1004. *
  1005. * @param string $string
  1006. * @param int $limit
  1007. *
  1008. * @return string
  1009. */
  1010. public static function summarize($string, $limit)
  1011. {
  1012. if (Strings::isString($string)) {
  1013. $tok = strtok($string, " ");
  1014. $text = "";
  1015. $words = '0';
  1016. while ($tok) {
  1017. $text .= " " . $tok;
  1018. $words++;
  1019. if (($words >= $limit) && ((substr($tok, -1) == "!") || (substr($tok, -1) == ".")))
  1020. break;
  1021. $tok = strtok(" ");
  1022. }
  1023. return ltrim($text);
  1024. } else {
  1025. return false;
  1026. }
  1027. }
  1028. /**
  1029. *
  1030. * @param string $string
  1031. *
  1032. * @return string
  1033. */
  1034. public static function stringReverse($string)
  1035. {
  1036. if (Strings::isString($string)) {
  1037. return Strings::processFunction($string, 'strrev');
  1038. } else {
  1039. return false;
  1040. }
  1041. }
  1042. /**
  1043. * @param $string
  1044. *
  1045. * @return bool
  1046. */
  1047. public static function containsHTML($string)
  1048. {
  1049. if (false == preg_match('#(?<=<)\w+(?=[^<]*?>)#', $string)) {
  1050. return false;
  1051. }
  1052. return true;
  1053. }
  1054. /**
  1055. *
  1056. * determines if a string contains newline characters
  1057. *
  1058. * @param string $string the string to test
  1059. *
  1060. * @return bool true, if newlines are found, false otherwise
  1061. */
  1062. public static function containsNewLines($string)
  1063. {
  1064. if (Strings::isString($string)) {
  1065. if (preg_match("/(%0A|%0D|\\n+|\\r+)/i", $string) != 0) {
  1066. return true;
  1067. } else {
  1068. return false;
  1069. }
  1070. }
  1071. return false;
  1072. }
  1073. /**
  1074. *
  1075. * this function formats text
  1076. *
  1077. * @param string $string the string of text to be converted
  1078. * @param string $mode the type of formatting to be done
  1079. * @param string $length the length, in # of chars, the string should be
  1080. * @param bool $use_title passed to str_truncate, whether to use the title
  1081. * attribute to display the full text
  1082. * @param string $allowed_tags tags allowed to be included
  1083. *
  1084. * @return string the same input string is redisplayed in a new format
  1085. */
  1086. public static function processText($string, $mode = "plain", $length = "", $use_title = false, $allowed_tags = null)
  1087. {
  1088. // first things first, if the string of text is
  1089. // less than 1 characters (IOW it is blank), then
  1090. // we just dump it and replace it with "--"
  1091. if (strlen($string) < 1) {
  1092. $string = "--";
  1093. } // otherwise, continue
  1094. else {
  1095. // process as plain text, with links and line breaks added
  1096. if ($mode == "plain") {
  1097. $string = Strings::plainTextDisplay($string);
  1098. } // process as true plain text
  1099. elseif ($mode == "stripped") {
  1100. $string = strip_tags($string);
  1101. $string = htmlspecialchars($string);
  1102. } elseif ($mode == "html") {
  1103. $string = strip_tags($string, $allowed_tags);
  1104. } // process as plain text, shortened to $length
  1105. elseif ($mode == "truncated") {
  1106. $length = (int)$length;
  1107. // Safety check: if the length param was set, we continue
  1108. if ($length > 0) {
  1109. $string = strip_tags($string);
  1110. //$string = htmlspecialchars($string);
  1111. $string = Strings::truncateString($string, $length, $use_title);
  1112. } // if the length parameter is not greater than zero,
  1113. // we have not passed the safety check and we should just
  1114. // treat it as "stripped"
  1115. else {
  1116. $string = strip_tags($string);
  1117. $string = htmlspecialchars($string);
  1118. }
  1119. } // if the mode hasn't been set, leave it alone
  1120. else {
  1121. return $string;
  1122. }
  1123. }
  1124. return $string;
  1125. }
  1126. /**
  1127. * @param $sString
  1128. * @param $aWords
  1129. * @param $attrs
  1130. *
  1131. * @return bool|mixed
  1132. */
  1133. public static function highlight($sString, $aWords, $attrs)
  1134. {
  1135. if (!is_array($aWords) || empty($aWords) || !is_string($sString)) {
  1136. return false;
  1137. }
  1138. $sWords = implode('|', $aWords);
  1139. return preg_replace('@\b(' . $sWords . ')\b@si', "<span $attrs>$1</span>", $sString);
  1140. }
  1141. /**
  1142. *
  1143. * pulls e-mail addresses from a string
  1144. *
  1145. * @param string $string the string we're looking in
  1146. *
  1147. * @return array an array of e-mail addresses
  1148. */
  1149. public static function extract_emails($string)
  1150. {
  1151. preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
  1152. return $matches[0];
  1153. }
  1154. /**
  1155. *
  1156. * takes a string of numbers and, for those numbers <10, adds '0' to them.
  1157. * i.e. '1' becomes '01'. Useful when making dates
  1158. *
  1159. * @param int $num
  1160. *
  1161. * @return string
  1162. */
  1163. public static function prependNum($num)
  1164. {
  1165. if ($num < 10) {
  1166. return "0" . $num;
  1167. }
  1168. return $num;
  1169. }
  1170. /**
  1171. *
  1172. * spell checks a single word
  1173. * requires pspell be bundled and configured (which is not the case as of PHP 5.3.0)
  1174. *
  1175. * @param string $word
  1176. * @param string $lang
  1177. *
  1178. * @return bool
  1179. */
  1180. public static function spellCheckWord($word, $lang = 'en')
  1181. {
  1182. $pspell_link = pspell_new($lang);
  1183. if (pspell_check($pspell_link, $word)) {
  1184. return true;
  1185. } else {
  1186. return false;
  1187. }
  1188. }
  1189. /**
  1190. * determines whether to display a string of text based on some condition
  1191. * may also prepend or append additional text based on the determination that
  1192. * the condition was satisfied.
  1193. *
  1194. * @param $string
  1195. * @param string $condition
  1196. * @param string $prepend
  1197. * @param string $append
  1198. * @param bool $echo
  1199. *
  1200. * @return string
  1201. */
  1202. public static function conditional_display($string, $condition = "strlen", $prepend = "", $append = "", $echo = false)
  1203. {
  1204. $output = '';
  1205. // POSSIBLE CONDITIONS
  1206. // strlen - string length greater than '2'
  1207. // bool - boolean
  1208. // isset - variable is set
  1209. // alnum - alphanumeric
  1210. // alpha - alphabetical only
  1211. // num - numeric only
  1212. // print - printable chars
  1213. switch ($condition) {
  1214. // String Length > 2
  1215. case "strlen":
  1216. if (strlen($string) < 2) {
  1217. $condition = false;
  1218. }
  1219. break;
  1220. // boolean
  1221. case "bool":
  1222. if (false === $string) {
  1223. $condition = false;
  1224. } else {
  1225. $condition = true;
  1226. }
  1227. break;
  1228. // Variable isset
  1229. case "isset":
  1230. if (isset($string)) {
  1231. $condition = true;
  1232. }
  1233. break;
  1234. // Alphanumeric only
  1235. case "alnum":
  1236. if (ctype_alnum($string)) {
  1237. $condition = true;
  1238. }
  1239. break;
  1240. // Alphabetical only
  1241. case "alpha":
  1242. if (ctype_alpha($string)) {
  1243. $condition = true;
  1244. }
  1245. break;
  1246. // Numeric only
  1247. case "num":
  1248. if (ctype_digit($string)) {
  1249. $condition = true;
  1250. }
  1251. break;
  1252. // Printable characters only
  1253. case "print":
  1254. if (ctype_print($string)) {
  1255. $condition = true;
  1256. }
  1257. break;
  1258. default:
  1259. $condition = true;
  1260. }
  1261. if ($condition == true) {
  1262. $output = $prepend . $string . $append;
  1263. } else {
  1264. $output = '';
  1265. }
  1266. if ($echo == true) {
  1267. echo $output = '';
  1268. } else {
  1269. return $output;
  1270. }
  1271. }
  1272. /**
  1273. * determines whether a string contains only numbers
  1274. *
  1275. * @param int $input_number the number being checked
  1276. *
  1277. * @return bool TRUE if only a number, else FALSE
  1278. */
  1279. public static function num_only($input_number)
  1280. {
  1281. if (!preg_match("/^([0-9]+)$/", $input_number)) {
  1282. return false;
  1283. } else {
  1284. return true;
  1285. }
  1286. }
  1287. /**
  1288. * cleans up strings so they can be used in URLS
  1289. *
  1290. * @author "Borek" - attributed to a post located at:
  1291. * http://drupal.org/node/63924
  1292. *
  1293. * @param string $string the string we're cleaning
  1294. *
  1295. * @return string the input string, ready to go
  1296. */
  1297. public static function pathauto_cleanstring($string)
  1298. {
  1299. $url = $string;
  1300. $url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
  1301. $url = trim($url, "-");
  1302. $url = iconv("utf-8", "us-ascii//TRANSLIT", $url); // TRANSLIT does the whole job
  1303. $url = strtolower($url);
  1304. $url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
  1305. return $url;
  1306. }
  1307. /**
  1308. *
  1309. * determines if there's any bad stuff in a string
  1310. *
  1311. * @param string $string the string to test
  1312. *
  1313. * @return bool true, if bad stuff has been found, false otherwise
  1314. */
  1315. public static function contains_bad_str($string)
  1316. {
  1317. if (Strings::isString($string)) {
  1318. $bad_strings = array(
  1319. "content-type:",
  1320. "mime-version:",
  1321. "multipart/mixed",
  1322. "Content-Transfer-Encoding:",
  1323. "bcc:",
  1324. "cc:",
  1325. "to:");
  1326. foreach ($bad_strings as $bad_string) {
  1327. if (eregi($bad_string, strtolower($string))) {
  1328. return true;
  1329. }
  1330. }
  1331. return false;
  1332. }
  1333. return false;
  1334. }
  1335. /**
  1336. * This function takes a numeric value, and adds commas where applicable.
  1337. * If you gave it the value of "2930829523", then it would return "2,930,829,523"
  1338. *
  1339. * @author tyutyu1@vodafone.hu
  1340. *
  1341. * @param int $value
  1342. *
  1343. * @return string
  1344. */
  1345. public static function num_comma($value)
  1346. {
  1347. if (strpos($value, ".")) {
  1348. $decimalval = substr($value, strpos($value, ".") + 1);
  1349. $value = substr($value, 0, strpos($value, "."));
  1350. }
  1351. $length = strlen($value);
  1352. for ($i = 3; $i < ($length); $i = $i + 3) {
  1353. $k = $i * (-1);
  1354. $chunks[count($chunks)] = substr($value, $k, 3);
  1355. }
  1356. $inarray = count($chunks) * 3;
  1357. $leftout = $length - $inarray;
  1358. $leftout = substr($value, 0, $leftout);
  1359. $finaltext = $leftout;
  1360. rsort($chunks);
  1361. for ($i = 0; $i < count($chunks); $i++) {
  1362. $finaltext .= "," . $chunks[$i];
  1363. }
  1364. if (strlen($decimalval) > 0) {
  1365. $finaltext .= "." . $decimalval;
  1366. }
  1367. return $finaltext;
  1368. }
  1369. /**
  1370. * @param $string
  1371. * @param bool $removeEmpty
  1372. *
  1373. * @return array|bool|string
  1374. */
  1375. public static function linesToArray($string, $removeEmpty = true)
  1376. {
  1377. if (Strings::isString($string)) {
  1378. $array = preg_split('/$\R?^/m', $string);
  1379. if ($removeEmpty === true) {
  1380. $array = Arrays::arrayRemoveEmpty($array);
  1381. }
  1382. return $array;
  1383. } else {
  1384. return false;
  1385. }
  1386. }
  1387. /**
  1388. * simple wrapper function to validate a string using the ctype_* functions
  1389. *
  1390. * @param string $string the string to be validated
  1391. * @param string $mode the validation mode, must adhere to one of the types below
  1392. *
  1393. * @return bool
  1394. */
  1395. public static function ctype_validate($string, $mode)
  1396. {
  1397. switch ($mode) {
  1398. case "alnum":
  1399. // check to see if $string ONLY contains alphanumeric characters
  1400. if (ctype_alnum($string)) {
  1401. return true;
  1402. }
  1403. break;
  1404. case "alpha":
  1405. // check to see if $string ONLY contains alphabetical characters
  1406. if (ctype_alpha($string)) {
  1407. return true;
  1408. }
  1409. break;
  1410. case "upper":
  1411. // check to see if $string ONLY contains uppercase letters
  1412. if (ctype_upper($string)) {
  1413. return true;
  1414. }
  1415. break;
  1416. case "lower":
  1417. // check to see if $string ONLY contains lowercase letters
  1418. if (ctype_lower($string)) {
  1419. return true;
  1420. }
  1421. break;
  1422. case "digit":
  1423. // check to see if $string ONLY contains numeric characters
  1424. if (ctype_digit($string)) {
  1425. return true;
  1426. }
  1427. break;
  1428. case "xdigit":
  1429. // check to see if $string is ALL hexadecimal digits
  1430. if (ctype_xdigit($string)) {
  1431. return true;
  1432. }
  1433. break;
  1434. case "space":
  1435. // check to see if $string ONLY contains whitespace characters (such as \n, \r, \t)
  1436. if (ctype_space($string)) {
  1437. return true;
  1438. }
  1439. break;
  1440. case "punct":
  1441. // check to see if $string ONLY contains punctuation characters
  1442. if (ctype_punct($string)) {
  1443. return true;
  1444. }
  1445. break;
  1446. case "print":
  1447. // check to see if $string ONLY contains printable
  1448. // characters.
  1449. // Or, to be more clear, checks that it only contains
  1450. // alphabetical, numeric, or punctuation characters
  1451. if (ctype_print($string)) {
  1452. return true;
  1453. }
  1454. break;
  1455. case "cntrl":
  1456. // check to see if $string ONLY contains control
  1457. // characters
  1458. if (ctype_cntrl($string)) {
  1459. return true;
  1460. }
  1461. break;
  1462. default:
  1463. return false;
  1464. }
  1465. }
  1466. /**
  1467. * changes an integer to a roman numeral
  1468. *
  1469. * @param int $integer the integer to convert
  1470. *
  1471. * @return string
  1472. */
  1473. public static function integerToRoman($integer)
  1474. {
  1475. // Convert the integer into an integer (just to make sure)
  1476. $integer = intval($integer);
  1477. $result = '';
  1478. // Create a lookup array that contains all of the Roman numerals.
  1479. $lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' =>
  1480. 400, 'C' => 100,
  1481. 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10,
  1482. 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
  1483. foreach ($lookup as $roman => $value) {
  1484. // Determine the number of matches
  1485. $matches = intval($integer / $value);
  1486. // Add the same number of characters to the string
  1487. $result .= str_repeat($roman, $matches);
  1488. // Set the integer to be the remainder of the integer and the value
  1489. $integer = $integer % $value;
  1490. }
  1491. // The Roman numeral should be built, return it
  1492. return $result;
  1493. }
  1494. /**
  1495. *
  1496. * @param string $string
  1497. *
  1498. * @return string
  1499. */
  1500. public static function utf8_htmlspecialchars($string)
  1501. {
  1502. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
  1503. }
  1504. /**
  1505. *
  1506. * @param string $string
  1507. *
  1508. * @return int
  1509. */
  1510. public static function utf8_strlen($string)
  1511. {
  1512. return strlen(utf8_decode($string));
  1513. }
  1514. /**
  1515. * @param $element
  1516. *
  1517. * @return int
  1518. */
  1519. public static function isLetters($element)
  1520. {
  1521. return preg_match("/[^A-z]/", $element);
  1522. }
  1523. /**
  1524. * @param $string
  1525. *
  1526. * @return array
  1527. */
  1528. public static function makeWordsArray($string)
  1529. {
  1530. $string = preg_split("/\s+/", $string, -1, PREG_SPLIT_NO_EMPTY);
  1531. foreach ($string AS $word) {
  1532. if (Strings::isLetters($word)) {
  1533. $output[] = strtolower($word);
  1534. }
  1535. }
  1536. return $output;
  1537. }
  1538. /**
  1539. * Count the number of bytes of a given string.
  1540. * Input string is expected to be ASCII or UTF-8 encoded.
  1541. * Warning: the function doesn't return the number of chars
  1542. * in the string, but the number of bytes.
  1543. *
  1544. * @param string $str The string to compute number of bytes
  1545. *
  1546. * @return int The length in bytes of the given string.
  1547. */
  1548. public static function strBytes($str)
  1549. {
  1550. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  1551. // Number of characters in string
  1552. $strlen_var = strlen($str);
  1553. // string bytes counter
  1554. $d = 0;
  1555. /*
  1556. * Iterate over every character in the string,
  1557. * escaping with a slash or encoding to UTF-8 where necessary
  1558. */
  1559. for ($c = 0; $c < $strlen_var; ++$c) {
  1560. $ord_var_c = ord($str{$d});
  1561. switch (true) {
  1562. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  1563. // characters U-00000000 - U-0000007F (same as ASCII)
  1564. $d++;
  1565. break;
  1566. c