I'm having problems to get a part of text only if it contains a substring. What i want to do is, given the next example:
1 - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
2 - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut et dolore magna aliqua."
And with a substring like "labore", get "labore" and the prev and next 20 characters:
1 - "...empor incididunt ut labore et dolore magna ali..."
Edit: I am developing the search box for a website, so given a word i want to return all the paragraphs who contains that word, but the paragraphs are long so i want to return only a part of it.
I managed to get something like this. It's a bit long-winded.
$string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
function searchStr($string, $search){
if(strpos($string, $search) !== FALSE){
echo "..." . substr($string, strpos($string, $search)-20, 20) . substr($string, strpos($string, $search), 20+strlen($search)) . "...";
}
}
$res = searchStr($string, "labore");
Returns
...empor incididunt ut labore et dolore magna ali...
$str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
$searchStr = 'labore';
$offsetLength = 20;
$pos = strpos($str, $searchStr);
if ($pos !== FALSE) // word found
echo substr($str, $pos - $offsetLength, $pos + strlen($searchStr) + $offsetLength);