我正在寻找一种在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);
我想要一个函数来返回所有字符串共有的部分。在这种情况下,它将返回""。
到目前为止我所拥有的是:
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 var将包含&#34;&#34;和&#34; 1&#34;
但我只想要答案 0 :(得分:0)
$strings[0] = "the black 51 o";
$strings[1] = "the black 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);
$final='';
$i=0;
$k=0;
//echo $count['the'].'2 1'.count($strings);
foreach($count as $key=>$value) {
//echo $countw.' '.count($strings).' ';
if((int)$value == count($strings) && $i==$k ){
if($i==0){
$final = $final.$key;
$i++;
}
else{
$final = $final.' '.$key;
$i++;
}
}
$k++;
}
echo $final;