我正在尝试获取PHP中两个字符串之间交集的第一段。这样的事情:
$a = 'Metric Bob Foundation A5, Lined, Pink & Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy & Green';
echo SOME_FUNCTION($a, $b);
// Expected output: 'Metric Bob Foundation A5, Lined, '
任何人都可以帮助我使用SOME_FUNCTION。
我在这里使用过这个:
function string_intersect($string1, $string2)
{
$array1 = $array2 = array();
for($i = 0, $j = 0, $s1_len = strlen($string1), $s2_len = strlen($string2);($i < $s1_len) || ($j < $s2_len); $i++, $j++) {
if($i < $s1_len) {
$array1[] = $string1[$i];
}
if($j < $s2_len) {
$array2[] = $string2[$j];
}
}
return implode('', array_intersect($array1, $array2));
}
但它返回: // Metric Bob Foundation A5,Lined,in&amp; RANE
哪个不太对。正如我所说,我只想要第一段。
提前致谢。
答案 0 :(得分:2)
function some_function($a, $b)
{
$result = '';
$len = strlen($a) > strlen($b) ? strlen($b) : strlen($a);
for($i=0; $i<$len; $i++)
{
if(substr($a, $i, 1) == substr($b, $i, 1))
{
$result .= substr($a, $i, 1);
}
else
{
break;
}
}
return $result;
}
$a = 'Metric Bob Foundation A5, Lined, Pink & Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy & Green';
echo some_function($a, $b);
输出
Metric Bob Foundation A5, Lined,
答案 1 :(得分:0)
function compString($a, $b){
$arr = explode(" ", $a);
$brr = explode(" ", $b);
$final = array();
for($i=0 ; $i < count($arr); $i++)
{
if($arr[$i] == $brr[$i])
$final[] = $arr[$i];
else
break;
}
echo implode(" ", $final);
}
用法
$a = 'Metric Bob Foundation A5, Lined, Pink & Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy & Green';
compString($a, $b);
答案 2 :(得分:0)
试试这个,
<?php
function get_match($a, $b)
{
$tmp='';
$a=str_split($a);
$b=str_split($b);
foreach($a as $key => $data)
{
if($data==$b[$key])
$tmp.=$data;
else
return $tmp;
}
return $tmp;
}
$a = 'Metric Bob Foundation A5, Lined, Pink & Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy & Green';
echo get_match($a, $b);
?>
<强>输出强>
Metric Bob Foundation A5, Lined,
答案 3 :(得分:0)
function getIntersection ($str1,$str2)
{
//get the min length of str1 & str2
$l = strlen($str1) <= strlen($str2)? strlen($str1):strlen($str2);
$intersection = "";
//substring length
$i = 0;
while($i < $l && (substr($str1,0,$i) == substr($str2,0,$i) ))
{
$i++;
}
return substr($str1,0,$i-1);
}
$a = 'Metric Bob Foundation A5, Lined,sdf Pink & Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy & Green';
echo getIntersection ($a, $b);
输出:
Metric Bob Foundation A5,Lined,