Is there a way of me finding an item in array from a similar but not identical needle?
For example: I want to find 'Allan' in an array but pull out 'Alan'
Is this something that is possible?
Is there a way of me finding an item in array from a similar but not identical needle?
For example: I want to find 'Allan' in an array but pull out 'Alan'
Is this something that is possible?
You can try metaphone and similar_text function inside array_filter anonymous function.
$items=array("trina","treena","allan","alan");
$key="trina";
$filteredItems = array_filter($items, function($elem) use($key){
$s=similar_text(metaphone($elem),metaphone($key),$p);
return ($p>80 && $elem!==$key) ; //if 80% similar
});
print_r($filteredItems);
output
Array ( [1] => treena )
Using Metaphone
function soundsLike($needle, $haystack){
$sounds = metaphone($needle);
foreach($haystack as $item){
if( $sounds == metaphone($item, strlen($sounds)))return $item;
}
}
echo soundsLike('will', ["trina","treena","alan","allan","William"]);
Output
"William"
As I said in the comments for another answer, metaphone is better then soundx the key thing here is metaphone lets you set the length, which can be dynamically based on the length of your needle. Specifically strlen($sounds)
.
The reason this is better is take the above example.
will = WL
William = WLM
And WL != WLM
however because we can set the length at 2 WL == WL
.
-Note- this only returns the first result, but it would be trivial to extend it to find them all. Like this
function soundsLike($needle, $haystack){
$sounds = metaphone($needle);
$matches = [];
foreach($haystack as $item){
if( $sounds == metaphone($item, strlen($sounds))) $matches[]=$item;
}
return $matches;
}
print_r(soundsLike('al', ["trina","treena","alan","allan","William"]));
Output
Array(
[0] => alan
[1] => allan
)