Dany
Dany

Reputation: 755

Find exact same string in multiple strings

The following example.

I have an array like this :

Array
(
    [0] =>  vlakke lasflenzen PN6
    [1] =>  vlakke lasflenzen PN10
    [2] =>  vlakke lasflenzen PN16
    [3] =>  vlakke lasflenzen PN25-40
)

I do not know what part of the strings will be the same. And i dont know if the pattern will stay the same. So i cannot explode() on spaces or something.

What i want to try is to extract the part of the srting that is exactly the same between all four of them but split between spaces.

So for this example I would need to extract 'vlakke lasflenzen' from the four strings based on compasison of them.

Can anyone help me?

Upvotes: 2

Views: 825

Answers (2)

Dany
Dany

Reputation: 755

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"

Upvotes: 0

John Bupit
John Bupit

Reputation: 10618

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);
}

Upvotes: 3

Related Questions