PHP String Chopping Excerpt

Hi there,

Let’s say I have a 400 character string… and there’s a string that I’m searching for in it (i.e. “#hashtag”). How can I only display the first 50 characters BEFORE and AFTER the #hashtag string?

Thanks in advanced!

Something like this?


<?php

$string = 'Lor em ipsum dolor sit #hastag amet, consectetur adipiscing elit. Sed metus augue, mollis non ornare eget, consectetur non eros. In hac habitasse platea dictumst. Duis egestas ultricies iaculis';
$before = 10;
$after = 10;
$find = '#hastag';

$pos = strpos($string, $find);

$start = $pos - $before; // work out where to start
$length = $start + $after + strlen($find) - 2; // work out where to end

$start = max($start, 0); // make sure we don't start before the beginning of the string
$length = min($length, strlen($string)); // make sure we don't end after the end of the string

$new = substr($string, $start, $length);

echo $new;

?>

@Panduola - great reply by immerse, but wouldn’t 10 words before and 10 words after the hashtag make a bit more sense?

Or, isolate and extract the sentence which contains the hashtag?

@Immerse thank you very much!

@Cups ahh! yes! This is actually what I meant to say… 10 words before and after… not characters. How might this look in code?

Thanks again!

Might look like this :

[fphp]split/fphp the string into words (ie on a space).

[fphp]array_search/fphp the #hashtag and return the target key number

then loop through the array and concat the words before and after the target


$string = 'Lor em ipsum dolor sit #hashtag amet, consectetur adipiscing elit. Sed metus augue, mollis non ornare eget, consectetur non eros. In hac habitasse platea dictumst. Duis egestas ultricies iaculis'; 

$words = split(" ", $string);

// var_dump( $words );

$tag_index = array_search('#hashtag', $words);

$tgt="";
foreach($words as $k=>$word){

if ( ($k > $tag_index - 10)  && ( $k < $tag_index + 10 ) ){
$tgt .= $word . ' ';
}

}

echo $tgt;

// Lor em ipsum dolor sit #hashtag amet, consectetur adipiscing elit. Sed metus augue, mollis non

There is probably a more efficient way of doing this, but that should get you started. If that string can be 1000s of words, I’d look at splitting on the #hashtag and get the last 10 words from array 1 and the first 10 words from array 2. You could also use [fphp]join/fphp instead of string concatenation.