orbitz
02-01-2007, 08:26 PM
Hello,
How do we search for similar words in a string
for example:
string: "My lake is running out of water while I am watering the garden. Walter, did you hear me?"
if the key word is 'water', the results would return the words:
water
watering
Wa
I am stuck on this
Thanks.
"water" would not return Wa. Only if you were searching on "wa" and it was case insensitive would that happen.
Here's one possible:
$(W|w)a(.+)^
Untested, and probably wrong. ;)
Saeven
02-05-2007, 01:37 AM
I know you called for a regular expression, but if code is an option, here's an easy, verbose way to do it:
$sentence = "My lake is running out of water while I am watering the garden. Walter, did you hear me?";
$keyword = "water";
$values = explode( " ", ereg_replace( "[^[:alnum:]]", " ", $sentence ) );
$substrings = array();
$keylen = strlen( $keyword );
foreach( $values as $word ){
if( !strlen( $word ) )
continue;
$word = strtolower( $word );
$shortest = ( ($l = strlen( $word )) > $keylen ) ? $keylen : $l;
$common = "";
for( $i = 0 ; $i < $shortest ; $i++ ){
if( $word[$i] != $keyword[$i] )
break;
$common .= $word[$i];
}
if( $common )
$substrings[$word] = $common;
}
print_r( $substrings );
Regular expressions will work, but not if the maximal substring isn't known without an expensive use of lookaheads and lookbehinds. Here's a regexp that finds your LCS for you:
"([A-Za-z])\1+"
Just match between your input, and the keyword.
Good luck!
Alex