Source for file str_pad.php

Documentation is available at str_pad.php

  1. <?php
  2. /**
  3. * @version $Id: str_pad.php,v 1.1 2007/09/09 20:39:49 pitlinz Exp $
  4. * @package utf8
  5. * @subpackage strings
  6. */
  7.  
  8. //---------------------------------------------------------------
  9. /**
  10. * Replacement for str_pad. $padStr may contain multi-byte characters.
  11. *
  12. * @author Oliver Saunders <oliver (a) osinternetservices.com>
  13. * @param string $input 
  14. * @param int $length 
  15. * @param string $padStr 
  16. * @param int $type ( same constants as str_pad )
  17. * @return string 
  18. * @see http://www.php.net/str_pad
  19. * @see utf8_substr
  20. * @package utf8
  21. * @subpackage strings
  22. */
  23. function utf8_str_pad($input, $length, $padStr = ' ', $type = STR_PAD_RIGHT) {
  24.     
  25.     $inputLen = utf8_strlen($input);
  26.     if ($length <= $inputLen) {
  27.         return $input;
  28.     }
  29.     
  30.     $padStrLen = utf8_strlen($padStr);
  31.     $padLen = $length - $inputLen;
  32.     
  33.     if ($type == STR_PAD_RIGHT) {
  34.         $repeatTimes = ceil($padLen / $padStrLen);
  35.         return utf8_substr($input . str_repeat($padStr, $repeatTimes), 0, $length);
  36.     }
  37.     
  38.     if ($type == STR_PAD_LEFT) {
  39.         $repeatTimes = ceil($padLen / $padStrLen);
  40.         return utf8_substr(str_repeat($padStr, $repeatTimes), 0, floor($padLen)) . $input;
  41.     }
  42.     
  43.     if ($type == STR_PAD_BOTH) {
  44.         
  45.         $padLen/= 2;
  46.         $padAmountLeft = floor($padLen);
  47.         $padAmountRight = ceil($padLen);
  48.         $repeatTimesLeft = ceil($padAmountLeft / $padStrLen);
  49.         $repeatTimesRight = ceil($padAmountRight / $padStrLen);
  50.         
  51.         $paddingLeft = utf8_substr(str_repeat($padStr, $repeatTimesLeft), 0, $padAmountLeft);
  52.         $paddingRight = utf8_substr(str_repeat($padStr, $repeatTimesRight), 0, $padAmountLeft);
  53.         return $paddingLeft . $input . $paddingRight;
  54.     }
  55.     
  56.     trigger_error('utf8_str_pad: Unknown padding type (' . $type . ')',E_USER_ERROR);
  57. }

Documentation generated on Thu, 08 Jan 2009 17:48:36 +0100 by phpDocumentor 1.4.0a2