php - Find exact same string in multiple strings -
the following example.
i have array :
array ( [0] => vlakke lasflenzen pn6 [1] => vlakke lasflenzen pn10 [2] => vlakke lasflenzen pn16 [3] => vlakke lasflenzen pn25-40 )
i not know part of strings same. , dont know if pattern stay same. cannot explode() on spaces or something.
what want try extract part of srting same between 4 of them split between spaces.
so example need extract 'vlakke lasflenzen' 4 strings based on compasison of them.
can me?
the problem you're talking called the longest common substring problem.
i found an implementation finding longest common substring in array of strings. mentioned in 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 $ci => $char) { foreach ($words $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 made here we've run through usort($longest_common_substring, $sort_by_strlen); return array_pop($longest_common_substring); }
Comments
Post a Comment