note 80247 deleted from function.substr by cmb

From: Date: Sun, 27 Oct 2019 09:07:18 +0000
Subject: note 80247 deleted from function.substr by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212824@lists.php.net to get a copy of this message
Note Submitter: highstrike at gmail dot com ---- Because i didnt see a function that would cut a phrase from a text (article or whatever) no matter where, front/middle/end and add ... + keeping the words intact, i wrote this: Usage: - The parameter $value if array will need the whole text and the portion you want to start from, a string. EG: cuttext(array($text, $string), 20). If the string is "have" and is near the beginning of the text, the function will cut like "I have a car ...", if the string is in the middle somewhere it will cut like "... if you want to have your own car ..." and if its somewhere near the end it will cut like "... and you will have one." - The $length parameter is self explanatory. Note: if you have just a string "127hh43h2h52312453jfks2" and you want to cut it, just use the function like so: cuttext($string, 10) and it will cut it like "127hh43h2h..." <?php //////////////////////////////////////////////////////// // Function: cuttext // Description: Cuts a string and adds ... function cuttext($value, $length) { if(is_array($value)) list($string, $match_to) = $value; else { $string = $value; $match_to = $value{0}; } $match_start = stristr($string, $match_to); $match_compute = strlen($string) - strlen($match_start); if (strlen($string) > $length) { if ($match_compute < ($length - strlen($match_to))) { $pre_string = substr($string, 0, $length); $pos_end = strrpos($pre_string, " "); if($pos_end === false) $string = $pre_string."..."; else $string = substr($pre_string, 0, $pos_end)."..."; } else if ($match_compute > (strlen($string) - ($length - strlen($match_to)))) { $pre_string = substr($string, (strlen($string) - ($length - strlen($match_to)))); $pos_start = strpos($pre_string, " "); $string = "...".substr($pre_string, $pos_start); if($pos_start === false) $string = "...".$pre_string; else $string = "...".substr($pre_string, $pos_start); } else { $pre_string = substr($string, ($match_compute - round(($length / 3))), $length); $pos_start = strpos($pre_string, " "); $pos_end = strrpos($pre_string, " "); $string = "...".substr($pre_string, $pos_start, $pos_end)."..."; if($pos_start === false && $pos_end === false) $string = "...".$pre_string."..."; else $string = "...".substr($pre_string, $pos_start, $pos_end)."..."; } $match_start = stristr($string, $match_to); $match_compute = strlen($string) - strlen($match_start); } return $string; } ?>

« previous php.notes (#212824) next »