note 107647 modified in function.substr-replace by danbrown
| From: | danbrown@php.net | Date: | Thu, 10 May 2012 20:25:39 +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-187802@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 is
yours?', 25) ?> This will result
in: My name is John, what is ...
--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 is yours?', 25) ?>
This will result in:
My name is John, what's ...
http://php.net/manual/en/function.substr-replace.php