TL DR
Using regular expressions:
longestSubstring(['Mymaxmuis', 'axmuis', 'muster'], buildRegexFrom('maxmuster'));
Full fragment
Using the regex below, you can match all the true substrings of the maxmuster string:
(?|((?: m(?=a) |(?<=m)a |a(?=x) |(?<=a)x |x(?=m) |(?<=x)m |m(?=u) |(?<=m)u |u(?=s) |(?<=u)s |s(?=t) |(?<=s)t |t(?=e) |(?<=t)e |e(?=r) |(?<=e)r )+)|([maxmuster]))
Live demo
You should prepare such a regular expression from a word like maxmuster so that you need to call its function:
function buildRegexFrom(string $word): string { // Split word to letters $letters = str_split($word); // Creating all side of alternations in our regex foreach ($letters as $key => $letter) if (end($letters) != $letter) $regex[] = "$letter(?={$letters[$key + 1]})|(?<=$letter){$letters[$key + 1]}"; // Return whole cooked pattern return "~(?|((?>".implode('|', $regex).")+)|([$word]))~i"; }
To return the longest match, you need to sort the results according to the length of the matches from the longest to the shortest. This means that you need to write another piece of code for it:
function longestSubstring(array $array, string $regex): array { foreach ($array as $value) { preg_match_all($regex, $value, $matches); usort($matches[1], function($a, $b) { return strlen($b) <=> strlen($a); }); // Store longest match being sorted $substrings[] = $matches[1][0]; } return $substrings; }
Putting it all together:
print_r(longestSubstring(['Mymaxmuis', 'axmuis', 'muster'], buildRegexFrom('maxmuster')));
Outputs:
Array ( [0] => maxmu [1] => axmu [2] => muster )
Php live demo
source share