【发布时间】:2014-08-30 22:58:11
【问题描述】:
我正在寻找一种方法来提取 PHP 中字符串的公共子字符串。例如,如果我有一个这样的数组:
$strings[0] = "the 1 o";
$strings[1] = "the 1 e";
$strings[2] = "the 2";
$strings[3] = "the rere";
$strings[4] = "the rere 2";
$strings[5] = "the rere1";
echo sametext($strings);
我想要一个函数来返回所有字符串共有的部分。在这种情况下,它将返回“the”。
到目前为止我所拥有的是:
function find($string){
$same = array();
$let = str_split($string[0]);
for($k=0 ; $k< count($string) ; $k++){
$let2 = str_split($string[$k]);
for($i=0 ; $i< count($let) ; $i++){
if($let[$i]==$let2[$i]){
$same[$k] = $same[$k].$let[$i];
}
}
}
最后我想构造句子,如果我这样做了
$strings[0] = "the black 1 o";
$strings[1] = "the blackr 1 e";
$strings[2] = "the black 1";
$strings[3] = "the black 1";
$strings[4] = "the black 1 2";
$strings[5] = "the black 1";
$all = array();
foreach($strings as $string) {
foreach(explode(' ', $string) as $value) {
$all[] = $value;
}
}
echo '<pre>';
$count = array_count_values($all);
//echo max($count);
$maxs = array_keys($count, max($count));
//echo $maxs;
//arsort($count);
print_r($maxs);
maxs 变量将包含“the”和“1”,但我只想要
【问题讨论】:
-
你有没有尝试过?如果是这样,请告诉我们什么。
-
听起来,它需要大量比较(想想看,稍微)......除此之外,它会匹配单词或字母吗?如果是这样,我将开始使用正则表达式来检索字符串中的所有单词(使用 preg,
\b-assertion 可能很有用)。总而言之,这听起来是一项相当复杂的任务......