note 58774 modified in function.str-pad by danbrown

From: Date: Sat, 02 Jul 2011 18:55:49 +0000
Subject: note 58774 modified in function.str-pad by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181191@lists.php.net to get a copy of this message
Hello, for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments. <?php $string = 'this is a test'; $oldLen = strlen($string); $direction = STR_PAD_BOTH; echo $string.'<br>'; echo str_const_len($string, 101, '#', $direction).'<br>'; echo $string.'<br>'; echo str_const_len($string, $oldLen, '#', $direction).'<br>'; echo $string.'<br><br>'."\n"; /* This function is an extension to str_pad, it manipulates the referenced string '$str' and stretches or reduces it to the specified length. It returns the number of characters, that were added or stripped. */ function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) { $origLen = strlen($str); if (strlen($str) < $len) { /* stretch string */ $str = str_pad($str, $len, $char, $str_pad_const); } else { /* reduce string */ switch ($str_pad_const) { case STR_PAD_LEFT: $str = substr($str, (strlen($str) - $len), $len); break; case STR_PAD_BOTH: $shorten = (int) ((strlen($str) - $len) / 2); $str = substr($str, $shorten, $len); break; default: $str = substr($str, 0, $len); break; } } return ($len - $origLen); } ?> --was-- Hello, i updated the function in my last post. it should be much more performant now. <?php $string = 'this is a test'; $oldLen = strlen($string); $direction = STR_PAD_BOTH; echo $string.'<br>'; echo str_const_len($string, 101, '#', $direction).'<br>'; echo $string.'<br>'; echo str_const_len($string, $oldLen, '#', $direction).'<br>'; echo $string.'<br><br>'."\n"; /* This function is an extension to str_pad, it manipulates the referenced string '$str' and stretches or reduces it to the specified length. It returns the number of characters, that were added or stripped. */ function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) { $origLen = strlen($str); if (strlen($str) < $len) { /* stretch string */ $str = str_pad($str, $len, $char, $str_pad_const); } else { /* reduce string */ switch ($str_pad_const) { case STR_PAD_LEFT: $str = substr($str, (strlen($str) - $len), $len); break; case STR_PAD_BOTH: $shorten = (int) ((strlen($str) - $len) / 2); $str = substr($str, $shorten, $len); break; default: $str = substr($str, 0, $len); break; } } return ($len - $origLen); } ?> http://php.net/manual/en/function.str-pad.php

« previous php.notes (#181191) next »