PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/api/class.String.php

https://bitbucket.org/xertoz/forge
PHP | 90 lines | 50 code | 11 blank | 29 comment | 9 complexity | 8fd15257cd5b366973c7718a4231f880 MD5 | raw file
  1. <?php
  2. /**
  3. * api.strings.php
  4. * Copyright 2008-2012 Mattias Lindholm
  5. *
  6. * This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
  7. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter
  8. * to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
  9. */
  10. namespace forge;
  11. class String {
  12. /**
  13. * Returns a random string
  14. * @param int length
  15. * @return string
  16. */
  17. static public function randomize($len) {
  18. $c = array(
  19. 'a','b','c','d','e','f','g','h','i','j','k',
  20. 'l','m','n','o','p','q','r','s','t','u','v',
  21. 'w','x','y','z'
  22. );
  23. $s = null;
  24. for ($n=0;$n<$len;$n++)
  25. $s .= (rand(0,2)>0) ? ((rand(0,2)==1) ? strtoupper($c[rand(0,sizeof($c)-1)]) : $c[rand(0,sizeof($c)-1)]) : rand(0,9);
  26. return $s;
  27. }
  28. /**
  29. * Shorten a string to a certain length (appends ... on shortening)
  30. * @param string String
  31. * @param int Maximum length
  32. * @return string
  33. */
  34. static public function shorten($String,$Length) {
  35. // Avoid bugs
  36. if (strlen($String) <= $Length)
  37. return $String;
  38. // Shorten it.
  39. $Short = substr($String,0,$Length);
  40. // Truncate it
  41. for ($i=strlen($Short)-1;$i>0;$i--)
  42. if ($String[$i] == ' ') {
  43. $Short = substr($String,0,strlen($Short)-(strlen($Short)-$i)).'...';
  44. if (strlen($Short) > $Length)
  45. $Short = \forge\String::shorten($Short,$Length);
  46. return $Short;
  47. }
  48. // Return the shortened
  49. return $Short;
  50. }
  51. /**
  52. * Convert given bytes into a proper size
  53. * @param mixed Byte number to convert
  54. * @return string Converted size
  55. * @throws Exception
  56. */
  57. static public function bytesize($number) {
  58. if (!is_numeric($number))
  59. throw new \Exception('Argument 1 is not expected number');
  60. $n = 0;
  61. while ($number > 1024) {
  62. $number /= 1024;
  63. $n++;
  64. }
  65. switch ($n) {
  66. default: $size = '?b'; break;
  67. case 0: $size = 'b'; break;
  68. case 1: $size = 'kb'; break;
  69. case 2: $size = 'Mb'; break;
  70. case 3: $size = 'Gb'; break;
  71. case 4: $size = 'Tb'; break;
  72. case 5: $size = 'Pb'; break;
  73. case 6: $size = 'Eb'; break;
  74. case 7: $size = 'Zb'; break;
  75. case 8: $size = 'Yb'; break;
  76. }
  77. return round($number,2).' '.$size;
  78. }
  79. }