The following example.
I have an array like this :
Array
(
[0] => vlakke lasflenzen PN6
[1] => vlakke lasflenzen PN10
[2] => vlak
The problem you're talking about is also called the longest common substring problem.
I found an implementation for finding the longest common substring in an array of strings. As mentioned in the original post, usage:
<?php
$array = array(
'PTT757LP4',
'PTT757A',
'PCT757B',
'PCT757LP4EV'
);
echo longest_common_substring($array);
// => T757
?>
The relevant code:
function longest_common_substring($words)
{
$words = array_map('strtolower', array_map('trim', $words));
$sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;');
usort($words, $sort_by_strlen);
$longest_common_substring = array();
$shortest_string = str_split(array_shift($words));
while (sizeof($shortest_string)) {
array_unshift($longest_common_substring, '');
foreach ($shortest_string as $ci => $char) {
foreach ($words as $wi => $word) {
if (!strstr($word, $longest_common_substring[0] . $char)) {
// No match
break 2;
} // if
} // foreach
$longest_common_substring[0].= $char;
} // foreach
array_shift($shortest_string);
}
// If we made it here then we've run through everything
usort($longest_common_substring, $sort_by_strlen);
return array_pop($longest_common_substring);
}
I finally got my own solutin to work.
$names = array[
'vlakke lasflenzen PN6',
'vlakke lasflenzen PN10',
'vlakke lasflenzen PN16',
'vlakke lasflenzen PN25-40'
];
$name = [];
$parts = [];
foreach ($names as $name) {
$parts[] = array_filter(explode(' ', $name));
}
foreach ($parts[0] as $index => $part) {
$match = true;
foreach ($parts as $item) {
if ($item[$index] !== $part)
$match = false;
}
if ($match)
$name[] = ucfirst($part);
}
echo implode(' ', $name);
# Output : "Vlakke Lasflenzen"