Any easy way to check if two or more characters ar

2019-07-13 02:30发布

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.

3条回答
倾城 Initia
2楼-- · 2019-07-13 02:39

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

查看更多
祖国的老花朵
3楼-- · 2019-07-13 02:51
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;
  }
}
查看更多
爷的心禁止访问
4楼-- · 2019-07-13 03:01

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) ;
查看更多
登录 后发表回答