str_pad.php 1.6 KB

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