PageRenderTime 23ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/sally/core/lib/sly/Util/String.php

https://bitbucket.org/SallyCMS/0.7
PHP | 390 lines | 188 code | 59 blank | 143 comment | 41 complexity | 2b43e3ef6af20ba9e1d08071b0df3888 MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
  4. *
  5. * This file is released under the terms of the MIT license. You can find the
  6. * complete text in the attached LICENSE file or online at:
  7. *
  8. * http://www.opensource.org/licenses/mit-license.php
  9. */
  10. /**
  11. * @ingroup util
  12. */
  13. class sly_Util_String {
  14. /**
  15. * Prüfen, ob Wert numerisch ist
  16. *
  17. * @param mixed $value der zu prüfende Wert
  18. * @return bool true, wenn der Wert verlustfrei in Zahl umgeformt werden kann, sonst false
  19. */
  20. public static function isInteger($value) {
  21. if (is_int($value)) return true;
  22. if (is_string($value) && strval(intval($value)) === $value) return true;
  23. return false;
  24. }
  25. /**
  26. * @param string $haystack
  27. * @param string $needle
  28. * @return boolean
  29. */
  30. public static function startsWith($haystack, $needle) {
  31. $haystack = (string) $haystack;
  32. $needle = (string) $needle;
  33. if (mb_strlen($needle) > mb_strlen($haystack)) return false;
  34. if ($haystack == $needle || mb_strlen($needle) == 0) return true;
  35. return mb_strstr($haystack, $needle) == $haystack;
  36. }
  37. /**
  38. * @param string $haystack
  39. * @param string $needle
  40. * @return boolean
  41. */
  42. public static function endsWith($haystack, $needle) {
  43. $haystack = (string) $haystack;
  44. $needle = (string) $needle;
  45. if (mb_strlen($needle) > mb_strlen($haystack)) return false;
  46. if ($haystack == $needle || mb_strlen($needle) == 0) return true;
  47. return mb_substr($haystack, -mb_strlen($needle)) == $needle;
  48. }
  49. /**
  50. * @param string $string
  51. * @return string
  52. */
  53. public static function strToUpper($string) {
  54. if (is_string($string)) {
  55. $string = str_replace('ß', 'ss', $string);
  56. $string = mb_strtoupper($string, 'UTF-8');
  57. }
  58. return $string;
  59. }
  60. /**
  61. * @param string $text
  62. * @return string
  63. */
  64. public static function replaceUmlauts($text) {
  65. static $specials = array(
  66. array('Ä', 'ä', 'á', 'à', 'é', 'è', 'Ö', 'ö', 'Ü' , 'ü' , 'ß', '&', 'ç'),
  67. array('Ae','ae', 'a', 'a', 'e', 'e', 'Oe', 'oe', 'Ue', 'ue', 'ss', '', 'c')
  68. );
  69. return str_replace($specials[0], $specials[1], $text);
  70. }
  71. /**
  72. * Format a number according to the current locale
  73. *
  74. * @param numeric $number
  75. * @param int $decimals
  76. * @return string
  77. */
  78. public static function formatNumber($number, $decimals = -1) {
  79. $locale = localeconv();
  80. $decimals = $decimals < 0 ? $locale['frac_digits'] : $decimals;
  81. return number_format($number, $decimals, $locale['decimal_point'], $locale['thousands_sep']);
  82. }
  83. /**
  84. * @param string $format
  85. * @param mixed $timestamp UNIX timestamp or datetime string (YYYY-MM-DD HH:MM:SS)
  86. * @return string
  87. */
  88. public static function formatStrftime($format, $timestamp = null) {
  89. if ($timestamp === null) $timestamp = time();
  90. elseif (!self::isInteger($timestamp)) $timestamp = strtotime($timestamp);
  91. $str = strftime($format, $timestamp);
  92. // Windows systems do not support UTF-8 locales, so we try to fix this
  93. // by manually converting the string. This should only happen on dev
  94. // machines, so don't worry about performance.
  95. if (PHP_OS === 'WINNT' && function_exists('iconv')) {
  96. $str = iconv('ISO-8859-1', 'UTF-8', $str);
  97. }
  98. return $str;
  99. }
  100. /**
  101. * @param mixed $timestamp UNIX timestamp or datetime string (YYYY-MM-DD HH:MM:SS)
  102. * @return string
  103. */
  104. public static function formatDate($timestamp = null) {
  105. return self::formatStrftime(t('dateformat'), $timestamp);
  106. }
  107. /**
  108. * @param mixed $timestamp UNIX timestamp or datetime string (YYYY-MM-DD HH:MM:SS)
  109. * @return string
  110. */
  111. public static function formatTime($timestamp = null) {
  112. return self::formatStrftime(t('timeformat'), $timestamp);
  113. }
  114. /**
  115. * @param mixed $timestamp UNIX timestamp or datetime string (YYYY-MM-DD HH:MM:SS)
  116. * @return string
  117. */
  118. public static function formatDatetime($timestamp = null) {
  119. return self::formatStrftime(t('datetimeformat'), $timestamp);
  120. }
  121. /**
  122. * Cut text to a maximum length
  123. *
  124. * Die folgende Funktion schneidet einen Text nach der einer bestimmten
  125. * Anzahl von Zeichen ab und hängt $suffix an, falls etwas abgeschnitten
  126. * wurde.
  127. *
  128. * @param string $text
  129. * @param int $maxLength
  130. * @param string $suffix
  131. * @return string
  132. */
  133. public static function cutText($text, $maxLength, $suffix = '...') {
  134. $text = preg_replace('/<br\s*\/>/', '##BR##', $text);
  135. $text = preg_replace('/<\/h[1-6]>/', '##BR####BR##', $text);
  136. $text = str_replace('</p>', '##BR####BR##', $text);
  137. $text = strip_tags($text);
  138. $text = str_replace('##BR##', '<br />', $text);
  139. $return = mb_substr($text, 0, $maxLength);
  140. // cut off trailing newlines (if input was something like "<p>foo</p>")
  141. while (self::endsWith($return, '<br />')) {
  142. $return = mb_substr($return, 0, -6);
  143. }
  144. if (mb_strlen($text) > $maxLength) {
  145. $return .= $suffix;
  146. }
  147. return $return;
  148. }
  149. /**
  150. * shortens a filename to a max lenght and leaves an optional suffix
  151. * prior to the extension
  152. *
  153. * @param string $name filename to be shorten
  154. * @param int $maxLength maximum string length
  155. * @param int $suffixLength length of last characters
  156. * @return string returns false on error
  157. */
  158. public static function shortenFilename($name, $maxLength, $suffixLength = 3) {
  159. if (mb_strlen($name) === 0 || $maxLength < 1 || $suffixLength < 0) {
  160. return false;
  161. }
  162. $pos = mb_strrpos($name, '.');
  163. if ($pos === false || $pos <= $maxLength) return $name;
  164. $shortname = mb_substr($name, 0, min($maxLength - $suffixLength, $pos));
  165. if ($maxLength - $suffixLength < $pos) {
  166. if ($suffixLength > 0) $shortname .= '…';
  167. $shortname .= mb_substr($name, $pos - $suffixLength, 3);
  168. }
  169. $shortname .= mb_substr($name, $pos);
  170. return $shortname;
  171. }
  172. /**
  173. * Dateigröße formatieren
  174. *
  175. * Diese Methode übernimmt eine Dateigröße in Byte und rechnet sie solange
  176. * in größere Einheiten um, bis eine sinnvolle Entsprechung gefunden wurde.
  177. * Werte, die kleiner als 1024 Byte sind, werden als "< 1 KB" zurückgegeben.
  178. * Aus diesem Grund sollte die Ausgabe dieser Methode natürlich wie jede
  179. * andere auch vor dem Einbetten in HTML durch htmlspecialchars() behandelt
  180. * werden.
  181. *
  182. * Die letzte Einheit ist ein Yottabyte.
  183. *
  184. * @param int $size die Dateigröße in Byte
  185. * @param int $precision
  186. * @param string $unit
  187. * @return string die Dateigröße im Format "X.YY _B" oder "< 1 KB"
  188. */
  189. public static function formatFilesize($size, $precision = 2, $unit = 'Bytes') {
  190. // Wir teilen in die Funktion immer durch 999 anstatt durch 1024, damit
  191. // als Größenangaben nicht "1023 KB", sondern "0,99 MB" errechnet werden.
  192. // Das ist benutzerfreundlicher.
  193. if ($size < 999) {
  194. return $size.' '.$unit;
  195. }
  196. $unitPrefixes = array('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y');
  197. while ($size > 999 && !empty($unitPrefixes)) {
  198. $size /= 1024.0;
  199. $unitPrefix = array_shift($unitPrefixes);
  200. }
  201. return self::formatNumber($size, $precision).' '.$unitPrefix.$unit;
  202. }
  203. /**
  204. * Führt eine Liste zusammen
  205. *
  206. * Diese Methode fügt eine Liste zu einem String zusammen. Im Unterschied
  207. * zum normalen implode() schreibt sie jedoch zwischen die letzten beiden
  208. * Elemente kein Komma, sondern per default ein " und ", um eine
  209. * menschenlesbarere Ausgabe zu erhalten.
  210. *
  211. * @param array $list die Liste von Elementen
  212. * @param string $last das Wort, das zwischen die letzten beiden Elemente gesetzt werden soll
  213. * @return string die Liste als String (zum Beispiel "a, b, c und d")
  214. */
  215. public static function humanImplode($list, $last = ' und ') {
  216. $list = array_values($list);
  217. switch (count($list)) {
  218. case 0: return '';
  219. case 1: return $list[0];
  220. case 2: return $list[0].$last.$list[1];
  221. default: return implode(', ', array_slice($list, 0, -1)).$last.$list[count($list)-1];
  222. }
  223. }
  224. /**
  225. * @param int $maxLen
  226. * @param int $minLen
  227. * @param string $charset
  228. * @return string
  229. */
  230. public static function getRandomString($maxLen = 5, $minLen = 1, $charset = null) {
  231. if ($minLen > $maxLen) {
  232. list($minLen, $maxLen) = array($maxLen, $minLen);
  233. }
  234. $count = mt_rand($minLen, $maxLen);
  235. $chars = $charset === null ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789' : $charset;
  236. $last = strlen($chars)-1;
  237. $s = '';
  238. for (; $count > 0; --$count) {
  239. $s .= $chars[mt_rand(0, $last)];
  240. }
  241. return str_shuffle($s);
  242. }
  243. /**
  244. * @param int $seconds
  245. * @return string
  246. */
  247. public static function secondsToAbsTime($seconds) {
  248. $time = '';
  249. $days = 0;
  250. $hours = 0;
  251. $minutes = 0;
  252. $seconds = (float) abs(intval($seconds));
  253. $days = floor($seconds / (24*3600)); $seconds -= $days * (24*3600);
  254. $hours = floor($seconds / 3600); $seconds -= $hours * 3600;
  255. $minutes = floor($seconds / 60); $seconds -= $minutes * 60;
  256. if ($days > 0) $time .= $days.'d ';
  257. $time .= sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
  258. return $time;
  259. }
  260. /**
  261. * @param double $seconds
  262. * @return string
  263. */
  264. public static function formatTimespan($seconds) {
  265. $ms = $seconds - floor($seconds);
  266. $formatted = self::secondsToAbsTime($seconds - $ms);
  267. list($hours, $mins, $secs) = explode(':', $formatted);
  268. $hours = explode('d', $hours);
  269. $days = (int) (count($hours) === 1 ? 0 : $hours[0]);
  270. $hours = (int) (count($hours) === 1 ? $hours[0] : $hours[1]);
  271. $mins = (int) $mins;
  272. $secs = (int) $secs;
  273. $list = array();
  274. if ($days) $list[] = sprintf('%d %s', $days, t('days_short'));
  275. if ($hours) $list[] = sprintf('%d %s', $hours, t('hours_short'));
  276. if ($mins) $list[] = sprintf('%d %s', $mins, t('minutes_short'));
  277. if ($secs) $list[] = sprintf('%d %s', $secs, t('seconds_short'));
  278. if ($ms) $list[] = sprintf('%d %s', $ms*1000, t('milliseconds_short'));
  279. return implode(' ', $list);
  280. }
  281. /**
  282. * @param string $text
  283. * @return string
  284. */
  285. public static function escapePHP($text) {
  286. return str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $text);
  287. }
  288. /**
  289. * @param string $filename
  290. * @return string
  291. */
  292. public static function getFileExtension($filename) {
  293. $lastDotPos = mb_strrpos($filename, '.');
  294. return $lastDotPos === false ? '' : mb_substr($filename, $lastDotPos + 1);
  295. }
  296. /**
  297. * @param mixed $value
  298. * @param array $options list of options for representations
  299. * @return string a human readable representation of $value
  300. */
  301. public static function stringify($value, array $options = array()) {
  302. switch (gettype($value)) {
  303. case 'integer':
  304. $value = $value;
  305. break;
  306. case 'string':
  307. $value = empty($options['quote']) ? $value : '"'.$value.'"';
  308. break;
  309. case 'boolean':
  310. $value = $value ? 'true' : 'false';
  311. break;
  312. case 'double':
  313. $value = str_replace('.', ',', round($value, 8));
  314. break;
  315. case 'array':
  316. case 'object':
  317. $value = print_r($value, true);
  318. break;
  319. case 'NULL':
  320. $value = 'null';
  321. break;
  322. case 'resource':
  323. default:
  324. ob_start();
  325. var_dump($value);
  326. $value = ob_get_clean();
  327. break;
  328. }
  329. return $value;
  330. }
  331. }