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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.