note 107647 modified in function.substr-replace by danbrown

From: Date: Thu, 10 May 2012 20:25:18 +0000
Subject: note 107647 modified in function.substr-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187801@lists.php.net to get a copy of this message
If anyone is in need, here is a simple function to chop string without chopping the word and leaving the sentence incomplete. This function chops the desired length of string and after that finds the last white space in the chopped string. After that it again chops the string to the position where the last white space was found and replace it with our desired filler:&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;function str_replacer($_string, $_length, $_replacer = &#39; ...&#39;){&#13;&#10;&#9;// Remove any HTML tags present in the string&#13;&#10;&#9;$_string = strip_tags($_string);&#13;&#10;&#9;if(strlen($_string) &#62; $_length){&#13;&#10;&#9;&#9;// Find the position for last white space after the string has been shortened to our desired length&#13;&#10;&#9;&#9;// This helps us to shorten the string without chopping the character or word from the middle&#13;&#10;&#9;&#9;// ASCII value for the white space is 32&#13;&#10;&#9;&#9;$_last_white_space_pos = strripos(substr($_string, 0, $_length), 32);&#13;&#10;&#9;&#9;return substr_replace($_string, $_replacer, $_last_white_space_pos);&#13;&#10;&#9;}&#13;&#10;&#9;else{&#13;&#10;&#9;&#9;return $_string;&#13;&#10;&#9;}&#13;&#10;}&#13;&#10;?&#62;&#13;&#10;&#13;&#10;// How to call&#13;&#10;&#60;?php echo str_replacer(&#39;My name is John, what is yours?&#39;, 25) ?&#62;&#13;&#10;&#13;&#10;This will result in:&#13;&#10;My name is John, what&#39;s ... --was-- If anyone is in need, here is a simple function to chop string without chopping the word and leaving the sentence incomplete. This function chops the desired length of string and after that finds the last white space in the chopped string. After that it again chops the string to the position where the last white space was found and replace it with our desired filler: <?php function str_replacer($_string, $_length, $_replacer = ' ...'){ // Remove any HTML tags present in the string $_string = strip_tags($_string); if(strlen($_string) > $_length){ // Find the position for last white space after the string has been shortened to our desired length // This helps us to shorten the string without chopping the character or word from the middle // ASCII value for the white space is 32 $_last_white_space_pos = strripos(substr($_string, 0, $_length), 32); return substr_replace($_string, $_replacer, $_last_white_space_pos); } else{ return $_string; } } ?> // How to call <?php echo str_replacer('My name is John, what\\'s yours?', 25) ?> This will result in: My name is John, what's ... http://php.net/manual/en/function.substr-replace.php

« previous php.notes (#187801) next »