2013-12-20 3 views
0

단어 배열과 불용어 배열이 있습니다. I는 불용어 배열에있는 단어의 배열에서 그 단어를 제거하려면,하지만 코드는 모든 단어 반환array_filter를 사용하여 배열 필터링

function stopwords($x){ 
     return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x); 
    }; 

$filteredArray = array_filter($wordArray, "stopwords"); 

왜?

+2

나를 위해 [Working] (http://codepad.viper-7.com/mxhGZE) 괜찮습니다. – Rikesh

+0

그래, 멋지다. –

+0

배열의 단어에 각 단어의 시작 또는 끝에 공백 문자가 없어야하므로 "red"는 실제로 ""red "'가 아니라" "red"'가됩니다. 공백 문자는 개행 문자 또는 기타 보이지 않는 문자를 포함하십시오. 실제 길이를 확인하십시오. –

답변

1
$wordArray = ["hello","red","world","is"]; 

function stopwords($x){ 
     return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x); 
    }; 

$filteredArray = array_filter($wordArray, "stopwords"); 
var_dump($filteredArray); 

# results out: 
array(2) { 
    [0] => string(5) "hello" 
    [2] => string(5) "world" 
} 

무엇이 돌아올 것이라고 생각하십니까?

'$ wordArray'입력이 문자열입니까 배열입니까?

+0

비록 그것이 내 잘못이고 코드는 괜찮 았지만 예제를 제공하기 위해이 솔루션을 사용합니다. – erdomester

0

// 배열을
$ wordArray = 배열 ​​('그', '있다', '에', '침대' '가고')를이어야한다;

// 부울
기능 중지 단어의 ($ x)를
{
수익을 반환해야는 preg_match을 ("/^(|!. A | 차량 | 빨간색 | |이 |에 |에 | 나 |의 | | for) $/", $ x);
}

// 필터 어레이
$ 필터 = array_filter ($ wordArray "중지 단어");

// 출력
echo "< pre>";
print_r ($ filter);

// 결과
배열
(
[0] => 그
[2] =>가는
[4] => 침대
)

0

시도해보십시오.

$words = array('apple','boll','cat','dog','elephant','got'); 
     $stopwords = array('cat','apple'); 

     foreach($words as $k=>$v) 
     { 
     if(in_array($v,$stopwords)){ 
      unset($words[$k]); 
     } 

     } 
print_r($words);