The requirement: search a string in a text-string (from DB) and show additional info around when presenting the result.
Examples:
text string = "The Quick Brown Fox Jumps Over the Lazy Dog"
search ==> result:
- "The" ==> "The Quick ..."
- "Quick" ==> "The Quick Brown ..."
- "Brown" ==> "... Quick Brown Fox ..."
- "Lazy" ==> "... the Lazy Dog"
- "ump" ==> "... Fox Jumps Over ..."
Rules are:
- aways complete word containing search string
- the word before if exists
- the word after if exists
- if there is something before the "before" word, show "..." at beginning
- if there is something after the "after" word, show "..." at end
How I solved it:
// initialize text
$text_found = '';
// first eliminate line feeds, tabs, double spaces etc
$tmp = str_replace(array( "\r\n", "\r", "\n", "\t", " " ), ' ', $text );
// now get starting position
$posStart = strpos( mb_convert_case( $tmp, MB_CASE_LOWER, 'UTF-8' ), $search );
// search first space before position
$space = strrpos( substr( $tmp, 0, $posStart +1 ), ' ', -1 );
if ( $space === FALSE ):
// no earlier space found, so start from beginning
$posStart = 0;
else:
$posStart = $space;
// check if there is an additional word before
$space = strrpos( substr( $tmp, 0, $space ), ' ', -1 );
if ( $space === FALSE ):
$text_found .= substr( $tmp, 0, $posStart );
else:
$text_found .= '... ' . substr( $tmp, $space, $posStart - $space );
endif;
endif;
// now we search first space after position
$space = strpos( substr( $tmp, $posStart +1 ), ' ' ) + 1;
if ( $space === FALSE ):
// no space after found, so add text till end
$text_found .= substr( $tmp, $posStart );
else:
// check if there is an additional word after
$space2 = strpos( substr( $tmp, $posStart + $space + 1 ), ' ' );
if ( $space2 === FALSE ):
$text_found .= substr( $tmp, $posStart );
else:
$text_found .= substr( $tmp, $posStart, $space2 + $space + 1 ) . ' ...';
endif;
endif;
Question is if there is a more elegance solution ? And if so how ?
Please see post below with my final outcome.