Jump to content

[SOLVED] Smart truncate search result


Davidloknl

Recommended Posts

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

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"
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.