str_pad.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * UTF8::str_pad
  4. * @param $str
  5. * @param $final_str_length
  6. * @param string $pad_str
  7. * @param int $pad_type
  8. * @return mixed|string
  9. * @throws ValueError| UTF8_Exception
  10. * @package KO7
  11. *
  12. * @copyright (c) 2007-2016 Kohana Team
  13. * @copyright (c) since 2016 Koseven Team
  14. * @copyright (c) 2005 Harry Fuecks
  15. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
  16. *
  17. */
  18. function _str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT)
  19. {
  20. //(PHP 8 >= PHP 8.3.0)
  21. // mb_str_pad — Pad a multibyte string to a certain length with another multibyte string
  22. if ( version_compare(PHP_VERSION, '8.3.0', '>=') ) {
  23. try {
  24. $res = mb_str_pad($str, $final_str_length, $pad_str, $pad_type);
  25. return $res;
  26. } catch (Exception $e) {
  27. throw new UTF8_Exception(
  28. "UTF8::str_pad: Unknown padding type (:pad_type)",
  29. [':pad_type' => $pad_type]);
  30. }
  31. } else {
  32. if (UTF8::is_ascii($str) and UTF8::is_ascii($pad_str))
  33. return str_pad($str, $final_str_length, $pad_str, $pad_type);
  34. $str_length = UTF8::strlen($str);
  35. if ($final_str_length <= 0 or $final_str_length <= $str_length)
  36. return $str;
  37. $pad_str_length = UTF8::strlen($pad_str);
  38. $pad_length = $final_str_length - $str_length;
  39. if ($pad_type == STR_PAD_RIGHT) {
  40. $repeat = ceil($pad_length / $pad_str_length);
  41. return UTF8::substr($str . str_repeat($pad_str, $repeat), 0, $final_str_length);
  42. }
  43. if ($pad_type == STR_PAD_LEFT) {
  44. $repeat = ceil($pad_length / $pad_str_length);
  45. return UTF8::substr(str_repeat($pad_str, $repeat), 0, floor($pad_length)) . $str;
  46. }
  47. if ($pad_type == STR_PAD_BOTH) {
  48. $pad_length /= 2;
  49. $pad_length_left = floor($pad_length);
  50. $pad_length_right = ceil($pad_length);
  51. $repeat_left = ceil($pad_length_left / $pad_str_length);
  52. $repeat_right = ceil($pad_length_right / $pad_str_length);
  53. $pad_left = UTF8::substr(str_repeat($pad_str, $repeat_left), 0, $pad_length_left);
  54. $pad_right = UTF8::substr(str_repeat($pad_str, $repeat_right), 0, $pad_length_right);
  55. return $pad_left . $str . $pad_right;
  56. }
  57. throw new UTF8_Exception("UTF8::str_pad: Unknown padding type (:pad_type)", [
  58. ':pad_type' => $pad_type,
  59. ]);
  60. }
  61. }