5

I'm trying to get the first segment of an intersection between two strings in PHP. Something like this:

$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, '

Could anyone help me with the SOME_FUNCTION.

I've used this one here:

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));
}

But it returns

Metric Bob Foundation A5, Lined, in &amp; rane

which is not quite right. As I said, I want just the first segment.

3

4 Answers 4

2

Demo

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 &amp; Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy &amp; Green';
echo some_function($a, $b);

Outputs

Metric Bob Foundation A5, Lined, 
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);
}

Usage

$a = 'Metric Bob Foundation A5, Lined, Pink &amp; Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy &amp; Green';
compString($a, $b);
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 &amp; Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy &amp; Green';
echo getIntersection ($a, $b);

Output:

Metric Bob Foundation A5, Lined,

Demo Link

0

Try this,

 <?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 &amp; Orange';
$b = 'Metric Bob Foundation A5, Lined, Navy &amp; Green';
echo get_match($a, $b);


?>

Output

 Metric Bob Foundation A5, Lined,

Not the answer you're looking for? Browse other questions tagged or ask your own question.