Any easy way to check if two or more characters are equal when comparing a four character string?

时间秒杀一切 提交于 2019-12-10 19:37:05

问题


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.


回答1:


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



回答2:


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:


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


来源:https://stackoverflow.com/questions/5804363/any-easy-way-to-check-if-two-or-more-characters-are-equal-when-comparing-a-four

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!