note 43899 modified in function.str-pad by danbrown

From: Date: Sat, 02 Jul 2011 18:56:45 +0000
Subject: note 43899 modified in function.str-pad by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181199@lists.php.net to get a copy of this message
If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this: <?php function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT) { $trans=array('$'=>$input,' '=>$pad); $output=str_pad('$',$len-strlen($input)+1,' ',$flag); $output=strtr($output,$trans); return $output; } echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;'); // will output <img src="some.gif">&nbsp;&nbsp; echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_BOTH); // will output &nbsp;<img src="some.gif">&nbsp; echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_LEFT); // will output &nbsp;&nbsp;<img src="some.gif"> ?> It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other. It also conveniently has the same syntax as str_pad. Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P --was-- If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this: <? function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT) { $trans=array('$'=>$input,' '=>$pad); $output=str_pad('$',$len-strlen($input)+1,' ',$flag); $output=strtr($output,$trans); return $output; } echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;'); // will output <img src="some.gif">&nbsp;&nbsp; echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_BOTH); // will output &nbsp;<img src="some.gif">&nbsp; echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_LEFT); // will output &nbsp;&nbsp;<img src="some.gif"> ?> It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other. It also conveniently has the same syntax as str_pad. Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P http://php.net/manual/en/function.str-pad.php

« previous php.notes (#181199) next »