programing

preg_match를 사용하여 배열에서 검색하는 방법은 무엇입니까?

starjava 2023. 9. 4. 19:29
반응형

preg_match를 사용하여 배열에서 검색하는 방법은 무엇입니까?

preg_match로 배열을 검색하려면 어떻게 해야 합니까?

예:

<?php
if( preg_match( '/(my\n+string\n+)/i' , array( 'file' , 'my string  => name', 'this') , $match) )
{
    //Excelent!!
    $items[] = $match[1];
} else {
    //Ups! not found!
}
?>

이 게시물에서 저는 당신이 요구하는 것을 하는 세 가지 다른 방법을 제공할 것입니다.마지막 스니펫을 사용하는 것이 가장 이해하기 쉬울 뿐만 아니라 코드도 꽤 깔끔하기 때문에 실제로 추천합니다.

배열에서 정규식과 일치하는 요소를 보려면 어떻게 해야 합니까?

이를 위하여 전용된 기능이 있고,preg_grep첫 번째 매개 변수로 정규식을 사용하고 두 번째 매개 변수로 배열을 사용합니다.

다음 예를 참조하십시오.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

산출량

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

문서화


하지만 나는 단지 지정된 그룹의 값을 얻고 싶을 뿐입니다. 어떻게요?

array_reduce와 함께preg_match에서는 이 문제를 깨끗한 방식으로 해결할 수 있습니다. 아래 내용을 참조하십시오.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher ($m, $str) {
  if (preg_match ('/^hello (\w+)/i', $str, $matches))
    $m[] = $matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

산출량

Array
(
    [0] => stackoverflow
    [1] => world
)

문서화


사용.array_reduce지루해 보이는데, 다른 방법이 없을까요?

네, 그리고 이것은 기존의 어떤 것도 사용하지 않지만 실제로 더 깨끗합니다.array_*또는preg_*기능.

이 방법을 두 번 이상 사용할 경우 함수로 포장합니다.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', $str, $m))
    $matches[] = $m[1];

문서화

preg_grep 사용

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);
$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

출력:

Array
(
   [1] => say hello
   [2] => hello stackoverflow
   [3] => hello world
)

사용할 수 있습니다.array_walk당신의 것을preg_match배열의 각 요소에 대한 함수입니다.

http://us3.php.net/array_walk

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

조금 더 걸릴 수도 있지만 이 버전을 제공할 수 있습니다!


$array = array (
    'tagid=1' => '1',
    "a" => "a", 
    "b" => "b", 
    "c" => "c",
    'tagid=2' => '2',
);

$regex = '/tagid=[0-9]+/i';

$tags = [];

foreach ($data as $key => $value) {
    if (preg_match($regex, $key)) {
        $tags[] = $value;
    }
}

// OUTPUT
$tags = array (
    0 => '1',
    1 => '2'
);

언급URL : https://stackoverflow.com/questions/8627334/how-to-search-in-an-array-with-preg-match

반응형