在PHP中提取字符串之间的相等部分
我正在寻找一种方法来提取PHP中字符串的公共子字符串。例如,如果我有这样一个数组:在PHP中提取字符串之间的相等部分,php,arrays,string,equals,Php,Arrays,String,Equals,我正在寻找一种方法来提取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); 我想要一个函数来返回所有字符串共有的部分。在这种情况下,
$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变量将包含和1,但我只想要您尝试过什么吗?如果是这样的话,让我们看看是什么。听起来,这需要很多比较——想想看,有一点。。。除此之外,它是否与单词或字母匹配?如果是这样,我将开始使用正则表达式来检索带有preg的字符串中的所有单词,\b-assertion可能会很有用。尽管如此,这听起来是一项相当复杂的任务。。。
$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;