2011-12-20 7 views
0

나는 단어 목록을 관리하는 텍스트 파일을 가지고 있습니다.일반적인 단어를 제거하는 PHP for 루프

내가하려는 것은이 함수에 문자열 (문장)을 전달하고 텍스트 파일에 단어가 있으면 문자열에서 단어를 제거하는 것입니다.

<?php 
error_reporting(0); 

$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning"; 

common_words($str1); 

function common_words($string) { 
$file = fopen("common.txt", "r") or exit("Unable to open file!"); 
$common = array(); 
while(!feof($file)) { 
    array_push($common,fgets($file)); 
    } 
fclose($file); 

$words = explode(" ",$string); 
print_r($words); 

for($i=0; $i <= count($words); $i+=1) { 
    for($j=0; $j <= count($common); $j+=1) { 
      if($words[$i] == $common[$j]){ 
      unset($words[$i]); 
      } 
     } 
    } 
} 
?> 

그러나 작동하지 않는 것 같습니다. 문자열의 일반적인 단어는 제거되지 않습니다. 대신 내가 시작한 것과 동일한 문자열을 얻고 있습니다.

내가 루프를 잘못하고 있다고 생각합니다. 올바른 접근 방식은 무엇이며 무엇이 잘못 되었습니까?

+0

이 숙제가 있습니까? –

+0

아니 내 프로젝트의 작은 부분입니다 ... – SupaOden

+0

$ 일반적인 배열을 인쇄하려고하면 하나의 배열 값에 전체 파일 내용을 삽입한다고 생각합니다. – YamahaSY

답변

1

 if(in_array($words[$i],$common)){ 

및 두 번째 for 루프를 제거하십시오.

+0

음 두? – Neal

+0

입력하기 전에 제출했습니다 – macintosh264

+0

글쎄 그게 바보 같았어요 :-P – Neal

1

str_replace() 사용해보십시오 :

foreach($common as $cword){ 
    str_replace($cwrod, '', $string); //replace word with empty string 
} 

또는 전체에서 : 라인

 if($words[$i] == $common[$j]){ 

변화 거기에

<?php 
error_reporting(0); 

$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning"; 

common_words($str1); 

function common_words(&$string) { //changes the actual string passed with & 

    $file = fopen("common.txt", "r") or exit("Unable to open file!"); 

    $common = array(); 
    while(!feof($file)) { 
     array_push($common,fgets($file)); 
    } 
    fclose($file); 

    foreach($common as $cword){ 
     str_replace($cword, '', $string); //replace word with empty string 
    } 
} 
?> 
+0

아마도 코딩 스타일을 위해서 fopen() 대신에 file_get_contents()를 사용했을 수도 있습니다. –

+0

@ Hikaru-Shindo lol true, 그러나 나는 그것에 들어가기를 원하지 않았습니다 : -P – Neal

+0

이 작업은'$ arr = array_merge (array_diff ($ words, $ common));'? – SupaOden