Davidloknl Posted August 24, 2008 Share Posted August 24, 2008 Hello All, What i would like to accomplish is to have a function that truncates a text and preserves the part around a given word. $text = "This is some tekst. It has some keyword like banana. I want to truncate this and just get a part of it."; $word = "banana"; $characters_before="18"; $characters_after="20"; Example: supertruncate($text, $word, $characters_before, $characters_after); Wanted result: "some keyword like banana. I want to truncate" Is there such function available? Does someone can point me in the right direction? My searches online keep giving me the "normal" truncate (first x characters) methods. Of course it would be nice if the function preserves words and ignores (or filters out) html code. Thanks in advance. David Link to comment https://forums.phpfreaks.com/topic/121097-solved-smart-truncate-search-result/ Share on other sites More sharing options...
unrelenting Posted August 24, 2008 Share Posted August 24, 2008 Try trim. http://us3.php.net/manual/en/function.trim.php or better yet substr... http://us3.php.net/manual/en/function.substr.php Never mind. I didn't read what you wanted carefully enough. Link to comment https://forums.phpfreaks.com/topic/121097-solved-smart-truncate-search-result/#findComment-624284 Share on other sites More sharing options...
sasa Posted August 24, 2008 Share Posted August 24, 2008 try <?php function supertruncate($text, $word, $characters_before, $characters_after){ $pos = strpos($text, $word); $start = $characters_before < $pos ? $pos - $characters_before : 0; $len = $pos + strlen($word) + $characters_after - $start; return substr($text, $start, $len); } $text = "This is some tekst. It has some keyword like banana. I want to truncate this and just get a part of it."; $word = "banana"; $characters_before="18"; $characters_after="20"; echo supertruncate($text, $word, $characters_before, $characters_after); //Wanted result: "some keyword like banana. I want to truncate" ?> Link to comment https://forums.phpfreaks.com/topic/121097-solved-smart-truncate-search-result/#findComment-624300 Share on other sites More sharing options...
Davidloknl Posted August 24, 2008 Author Share Posted August 24, 2008 @unrelenting: Thanks for the effort. @Sasa: Perfect, thanks! Exactly what i needed. Link to comment https://forums.phpfreaks.com/topic/121097-solved-smart-truncate-search-result/#findComment-624311 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.