3

I have to compare two strings such as INTU and IXTE and check if two or more of the characters are the same. With the previous two strings, I'd want to return true, since the I and the T are the same.

Order of letters in the string ends up being irrelevant as each character can not appear in different positions in the string. It seems like there should be an easy way to do this.

rapidash
  • 278
  • 3
  • 14

3 Answers3

8

look at similar_text(). The following code is untested but i think it would work as you want.

$a = "INTU";
$b = "IXTE";

$is_match = ( similar_text($a , $b) >= 2) ;
Sabeen Malik
  • 10,776
  • 4
  • 32
  • 50
  • This is a nice solution, although I think `$is_match = ( similar_text($a , $b) >= 0.5);` may be correct, as `similar_text` seems to return a percentage – rapidash Apr 27 '11 at 14:12
  • If you pass the third parameter only then it would return the percentage. From the manual `By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings. ` – Sabeen Malik Apr 27 '11 at 14:15
1

You could use the array_intersect() function of php It returns all intersections. So if it does return more than 2, you return true.

But it doesnt accept string elements as input, so you would need to fill an array with the chars of the string you want to compare.

Manual: http://php.net/manual/de/function.array-intersect.php

nohero
  • 82
  • 1
  • 3
  • This would work nicely, but `strings` are not `array`s of characters. Is there any way to treat them as such for use with this function? – rapidash Apr 27 '11 at 13:11
  • you can access a single character of a string simply with $string[0] so you can loop and get all single chars. if foreach doesn't work use strlen to make the correct loop. – nohero Apr 27 '11 at 13:16
  • did forget to mention: the top solution looks nicer, so this way would only be yours if you like to know WHICH elements did match – nohero Apr 27 '11 at 13:27
  • `count(array_intersect(str_split($a), str_split($b))) >= 2)` is how I ended up writing this, but now that I know the above, that'll be changed. – rapidash Apr 27 '11 at 14:09
0
function compare_strings($str1, $str2)
{
  $count=0;
  $compare[] = substr($str1, 0, 1);
  $compare[] = substr($str1, 1, 1);
  $compare[] = substr($str1, 2, 1);
  $compare[] = substr($str1, 3, 1);

  foreach($compare as $string)
  {
    if(strstr($str2, $string)) { $count++; }
  } 

  if($count>1) 
  {
    return TRUE;
  }else{
    return FALSE;
  }
}
David Houde
  • 4,745
  • 1
  • 16
  • 28