I have an array with a bunch of words. E.g:
array( developer,develop,development,design,designer,designing )
I want to be able to group these words together with their similar words so I'd get something like this:
array(
array( develop, developer, development ),
array( design, designer, designing ),
);
What would be the best way to do this in PHP?
You can do it easily using metaphone():
$result = array();
foreach ($array as $word) {
$result[metaphone($word, 2)][] = $word;
}
print_r($result); will show:
Array
(
[TF] => Array
(
[0] => developer
[1] => develop
[2] => development
)
[TS] => Array
(
[0] => design
[1] => designer
[2] => designing
)
)
A way is comming to my mind
$array = array( 'developer','develop','development','design','designer','designing' );
function matchWords(array $in,$pad='4')
{
$ret = array();
foreach ($in as $v) {
$sub = substr($v, 0, $pad);
if (!isset($ret[$sub])) {
$ret[$sub] = array();
}
$ret[$sub][] = $v;
}
return array_values($ret);
}
print_r(matchWords($array,4));
Array
(
[0] => Array
(
[0] => developer
[1] => develop
[2] => development
)
[1] => Array
(
[0] => design
[1] => designer
[2] => designing
)
)
This matches the $pad first letters of your array values and create a key on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With