str_pad.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. /**
  3. * UTF8::str_pad
  4. *
  5. * @package Kohana
  6. * @author Kohana Team
  7. * @copyright (c) Kohana Team
  8. * @copyright (c) 2005 Harry Fuecks
  9. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
  10. */
  11. function _str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT)
  12. {
  13. if (UTF8::is_ascii($str) AND UTF8::is_ascii($pad_str))
  14. return str_pad($str, $final_str_length, $pad_str, $pad_type);
  15. $str_length = UTF8::strlen($str);
  16. if ($final_str_length <= 0 OR $final_str_length <= $str_length)
  17. return $str;
  18. $pad_str_length = UTF8::strlen($pad_str);
  19. $pad_length = $final_str_length - $str_length;
  20. if ($pad_type == STR_PAD_RIGHT)
  21. {
  22. $repeat = ceil($pad_length / $pad_str_length);
  23. return UTF8::substr($str.str_repeat($pad_str, $repeat), 0, $final_str_length);
  24. }
  25. if ($pad_type == STR_PAD_LEFT)
  26. {
  27. $repeat = ceil($pad_length / $pad_str_length);
  28. return UTF8::substr(str_repeat($pad_str, $repeat), 0, floor($pad_length)).$str;
  29. }
  30. if ($pad_type == STR_PAD_BOTH)
  31. {
  32. $pad_length /= 2;
  33. $pad_length_left = floor($pad_length);
  34. $pad_length_right = ceil($pad_length);
  35. $repeat_left = ceil($pad_length_left / $pad_str_length);
  36. $repeat_right = ceil($pad_length_right / $pad_str_length);
  37. $pad_left = UTF8::substr(str_repeat($pad_str, $repeat_left), 0, $pad_length_left);
  38. $pad_right = UTF8::substr(str_repeat($pad_str, $repeat_right), 0, $pad_length_right);
  39. return $pad_left.$str.$pad_right;
  40. }
  41. throw new UTF8_Exception("UTF8::str_pad: Unknown padding type (:pad_type)", [
  42. ':pad_type' => $pad_type,
  43. ]);
  44. }