programing

대소문자를 구분하지 않는 PHP in_array 함수

bestcode 2023. 2. 6. 23:33
반응형

대소문자를 구분하지 않는 PHP in_array 함수

사용 시 대소문자를 구분하지 않는 비교가 가능합니까?in_array기능하고 있습니까?

따라서 다음과 같은 소스 어레이를 사용할 수 있습니다.

$a= array(
 'one',
 'two',
 'three',
 'four'
);

다음 검색은 모두 true로 반환됩니다.

in_array('one', $a);
in_array('two', $a);
in_array('ONE', $a);
in_array('fOUr', $a);

어떤 기능 또는 기능 집합이 동일한 기능을 수행합니까?난 그렇게 생각하지 않아.in_array그 자체가 할 수 있어요.

검색어를 소문자로 변환하기만 하면 됩니다.

if (in_array(strtolower($word), $array)) { 
  ...

물론 어레이에 대문자가 포함되어 있는 경우는, 다음의 조작을 실시할 필요가 있습니다.

$search_array = array_map('strtolower', $array);

검색해보세요.해도 소용없다strtolower전체 어레이에서 모든 검색을 수행할 수 있습니다.

그러나 배열 검색은 선형입니다.대규모 어레이를 사용하거나 이 작업을 많이 수행할 경우 검색어를 어레이의 키에 넣는 것이 좋습니다.이렇게 하면 액세스 속도가 향상됩니다.

$search_array = array_combine(array_map('strtolower', $a), $a);

그리고나서

if ($search_array[strtolower($word)]) { 
  ...

여기서 유일한 문제는 어레이 키가 고유해야 하기 때문에 충돌(예: "One"와 "One")이 발생하면 하나를 제외한 모든 키가 손실된다는 것입니다.

function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

매뉴얼에서

다음을 사용할 수 있습니다.

$a= array(
 'one',
 'two',
 'three',
 'four'
);

print_r( preg_grep( "/ONe/i" , $a ) );
function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

출처: php.net in_array 매뉴얼 페이지.

in_array를 사용하는 경우 대소문자를 구분하지 않는 방법을 다음에 나타냅니다.

in_array()에서 대소문자를 구분하지 않습니다.

foreach($searchKey as $key => $subkey) {

     if (in_array(strtolower($subkey), array_map("strtolower", $subarray)))
     {
        echo "found";
     }

}

보통 대소문자를 구분합니다.

foreach($searchKey as $key => $subkey) {

if (in_array("$subkey", $subarray))

     {
        echo "found";
     }

}

위의 내용은 어레이에 문자열만 포함할 수 있지만 어레이에 다른 어레이도 포함할 수 있다고 가정할 때 맞습니다.또한 in_array() 함수는 $needle에 대해 어레이를 받아들일 수 있으므로 $needle이 어레이이고 $haystack이 다른 어레이를 포함하고 있으면 array_map('strtolower', $haystack)은 동작하지 않지만 "PHP warning: strtolower() 파라미터 1이 지정될 것으로 예상합니다.

예:

$needle = array('p', 'H');
$haystack = array(array('p', 'H'), 'U');

그래서 대소문자를 구분하고 대소문자를 구분하지 않는 in_array() 체크로 도우미 클래스를 만들었습니다.strtolower() 대신 mb_strtolower()를 사용하고 있기 때문에 다른 인코딩을 사용할 수 있습니다.코드는 다음과 같습니다.

class StringHelper {

public static function toLower($string, $encoding = 'UTF-8')
{
    return mb_strtolower($string, $encoding);
}

/**
 * Digs into all levels of an array and converts all string values to lowercase
 */
public static function arrayToLower($array)
{
    foreach ($array as &$value) {
        switch (true) {
            case is_string($value):
                $value = self::toLower($value);
                break;
            case is_array($value):
                $value = self::arrayToLower($value);
                break;
        }
    }
    return $array;
}

/**
 * Works like the built-in PHP in_array() function — Checks if a value exists in an array, but
 * gives the option to choose how the comparison is done - case-sensitive or case-insensitive
 */
public static function inArray($needle, $haystack, $case = 'case-sensitive', $strict = false)
{
    switch ($case) {
        default:
        case 'case-sensitive':
        case 'cs':
            return in_array($needle, $haystack, $strict);
            break;
        case 'case-insensitive':
        case 'ci':
            if (is_array($needle)) {
                return in_array(self::arrayToLower($needle), self::arrayToLower($haystack), $strict);
            } else {
                return in_array(self::toLower($needle), self::arrayToLower($haystack), $strict);
            }
            break;
    }
}
}
/**
 * in_array function variant that performs case-insensitive comparison when needle is a string.
 *
 * @param mixed $needle
 * @param array $haystack
 * @param bool $strict
 *
 * @return bool
 */
function in_arrayi($needle, array $haystack, bool $strict = false): bool
{

    if (is_string($needle)) {

        $needle = strtolower($needle);

        foreach ($haystack as $value) {

            if (is_string($value)) {
                if (strtolower($value) === $needle) {
                    return true;
                }
            }

        }

        return false;

    }

    return in_array($needle, $haystack, $strict);

}


/**
 * in_array function variant that performs case-insensitive comparison when needle is a string.
 * Multibyte version.
 *
 * @param mixed $needle
 * @param array $haystack
 * @param bool $strict
 * @param string|null $encoding
 *
 * @return bool
 */
function mb_in_arrayi($needle, array $haystack, bool $strict = false, ?string $encoding = null): bool
{

    if (null === $encoding) {
        $encoding = mb_internal_encoding();
    }

    if (is_string($needle)) {

        $needle = mb_strtolower($needle, $encoding);

        foreach ($haystack as $value) {

            if (is_string($value)) {
                if (mb_strtolower($value, $encoding) === $needle) {
                    return true;
                }
            }

        }

        return false;

    }

    return in_array($needle, $haystack, $strict);

}

아래 코드와 같은 배열에서 비활성 값을 확인하는 간단한 함수를 작성했습니다.

기능:

function in_array_insensitive($needle, $haystack) {
   $needle = strtolower($needle);
   foreach($haystack as $k => $v) {
      $haystack[$k] = strtolower($v);
   }
   return in_array($needle, $haystack);
}

사용방법:

$array = array('one', 'two', 'three', 'four');
var_dump(in_array_insensitive('fOUr', $array));
$a = [1 => 'funny', 3 => 'meshgaat', 15 => 'obi', 2 => 'OMER'];  

$b = 'omer';

function checkArr($x,$array)
{
    $arr = array_values($array);
    $arrlength = count($arr);
    $z = strtolower($x);

    for ($i = 0; $i < $arrlength; $i++) {
        if ($z == strtolower($arr[$i])) {
            echo "yes";
        }  
    } 
};

checkArr($b, $a);
$user_agent = 'yandeX';
$bots = ['Google','Yahoo','Yandex'];        
        
foreach($bots as $b){
     if( stripos( $user_agent, $b ) !== false ) return $b;
}

regex 대소문자를 구분하지 않는 검색을 사용하면 건초 스택과 니들 모두에서 대소문자가 무시됩니다.

$haystack = array('MacKnight', 'MacManus', 'MacManUS', 'MacMurray');
$needle='MacMANUS';
$regex='/'.$needle.'/i';
$matches  = preg_grep ($regex, $haystack);
if($m=current($matches)){ // find first case insensitive match
   echo 'match found: '.$m;
}else{
   echo 'no match found.';
} 
  • in_array는 다음 파라미터를 받아들입니다.in_array(search,array,type)
  • 검색 매개 변수가 문자열이고 type 매개 변수가 TRUE로 설정된 경우 검색은 대소문자를 구분합니다.
  • 따라서 검색에서 대소문자를 무시하려면 다음과 같이 사용하면 됩니다.

$a = 배열('1', '2', '3', '4');

$b = in_array ('ONE', $a, false );

언급URL : https://stackoverflow.com/questions/2166512/php-case-insensitive-in-array-function

반응형