php - Most efficient way to find matching words from paragraph -
i have paragraph have parse different keywords. example, paragraph:
"i want make change in world. want make better place live. peace, love , harmony. life about. can make our world place live"
and keywords are
"world", "earth", "place"
i should report whenever have match , how many times.
output should be:
"world" 2 times , "place" 1 time
currently, converting paragraph strings array of characters , matching each keyword of array contents. wasting resources. please guide me efficient way.( using php)
as @casimirethippolyte commented, regex better means word boundaries can used. further caseless matching possible using i
flag. use preg_match_all return value:
returns number of full pattern matches (which might zero), or false if error occurred.
the pattern matching 1 word is: /\bword\b/i
. generate array keys word values search $words
, values mapped word-count, preg_match_all returns:
$words = array("earth", "world", "place", "foo"); $str = "at earth hour world-lights go out , make every place on world dark"; $res = array_combine($words, array_map( function($w) use (&$str) { return preg_match_all('/\b'.preg_quote($w,'/').'\b/i', $str); }, $words));
print_r($res);
test @ eval.in outputs to:
array ( [earth] => 1 [world] => 2 [place] => 1 [foo] => 0 )
used preg_quote escaping words not necessary, if know, don't contain specials. use of inline anonymous functions array_combine
php 5.3 required.
Comments
Post a Comment