note 107647 added to function.substr-replace

From: Date: Thu, 23 Feb 2012 18:54:20 +0000
Subject: note 107647 added to function.substr-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-186323@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: <?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 ... ---- Server IP: 69.147.83.197 Probable Submitter: 49.244.157.48 ---- Manual Page -- http://www.php.net/manual/en/function.substr-replace.php Edit -- https://master.php.net/note/edit/107647 Del: integrated -- https://master.php.net/note/delete/107647/integrated Del: useless -- https://master.php.net/note/delete/107647/useless Del: bad code -- https://master.php.net/note/delete/107647/bad+code Del: spam -- https://master.php.net/note/delete/107647/spam Del: non-english -- https://master.php.net/note/delete/107647/non-english Del: in docs -- https://master.php.net/note/delete/107647/in+docs Del: other reasons-- https://master.php.net/note/delete/107647 Reject -- https://master.php.net/note/reject/107647 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186323) next »