3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $names = array( '真三国无双', '无双剑姬', '虚无', '一时无两', '南无阿弥陀佛', '崖山之后无中国', ); //拆分词语为单个字符 function split_name($name) { preg_match_all("/./u", $name, $arr); return $arr[0]; } //最长公共子序列 function LCS($str_1, $str_2) { $len_1 = strlen($str_1); $len_2 = strlen($str_2); $len = $len_1 > $len_2 ? $len_1 : $len_2; $dp = array(); for ($i = 0; $i <= $len; $i++) { $dp[$i] = array(); $dp[$i][0] = 0; $dp[0][$i] = 0; } for ($i = 1; $i <= $len_1; $i++) { for ($j = 1; $j <= $len_2; $j++) { if ($str_1[$i - 1] == $str_2[$j - 1]) { $dp[$i][$j] = $dp[$i - 1][$j - 1] + 1; } else { $dp[$i][$j] = $dp[$i - 1][$j] > $dp[$i][$j - 1] ? $dp[$i - 1][$j] : $dp[$i][$j - 1]; } } } return $dp[$len_1][$len_2]; } function search($name) { Global $names; $sort_list = array(); if (mb_strlen($name, 'utf-8') != strlen($name)) { // 是否全英文字符 $arr_1 = array_unique(split_name($name)); foreach ($names as $value) { $arr_2 = array_unique(split_name($value)); $similarity = count($arr_2) - count(array_diff($arr_2, $arr_1)); $sort_list[$value] = $similarity; } } else { foreach ($names as $value) { $similarity = LCS($name, $value); $sort_list[$value] = $similarity; } } arsort($sort_list); return $sort_list; } header('content-type:text/html;charset=utf-8'); print_r(search('无'));
based on RWhMN
Output for 7.0.0 - 7.2.0
Array ( [真三国无双] => 1 [无双剑姬] => 1 [虚无] => 1 [一时无两] => 1 [南无阿弥陀佛] => 1 [崖山之后无中国] => 1 )
Output for 5.4.0 - 5.6.28
Array ( [南无阿弥陀佛] => 1 [崖山之后无中国] => 1 [一时无两] => 1 [虚无] => 1 [无双剑姬] => 1 [真三国无双] => 1 )