2017-07-24 70 views
-1

我有這樣的代碼: -如何顯示和計算過濾結果?

<?php 
    $string="cari naskah dengan edisi tahun 2017"; 
    $stopwords = array("dan", "dengan"); 
     foreach ($stopwords as &$word) { 
     $word = '/\b' . preg_quote($word, '/') . '\b/'; 
     } 
    $filter=preg_replace($stopwords,'', $string); 
    echo $filter; 
    $word = explode(" ",$filter); 
     $jumlah = count($word); 
     echo "<table border='1'>"; 
     echo "<tr><th>Kata</th></tr>"; 
     for ($i=0; $i <$jumlah; $i++) 
     { 
      echo "<tr><td>"; 
      echo "word $i = $word[$i]"; 
      echo "</td></tr>"; 
     } 
     echo "</table>"; 
     echo "<b>Number of words : " .$jumlah. "</b><br>"; 
     echo "<br />"; 
    ?> 

輸出: enter image description here

但是,我的預期輸出:

cari naskah edisi tahun 2017 
Kata 
word 0 = cari 
word 1 = naskah 
word 2 = edisi 
word 3 = tahun 
word 4 = 2017 
Number of words : 5 

如何這個問題的解決?謝謝

回答

0

簡單的使用功能!in_array()

<?php 
    $string="cari naskah dengan edisi tahun 2017"; 
    $stopwords = array("dan", "dengan"); 

     $word = explode(" ",$string); 
     $jumlah = count($word); 
     echo "<table border='1'>"; 
     echo "<tr><th>Kata</th></tr>"; 
     $i=0; 
     foreach($word as $key=>$row) 
     { 
      if(!in_array($row,$stopwords)){ 
      //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

       echo "<tr><td>"; 
       echo "word $i = $word[$i]"; 
       echo "</td></tr>"; 

       $i++; 
      } 


     } 
     echo "</table>"; 
     echo "<b>Number of words : " .$i. "</b><br>"; 
     echo "<br />"; 
?> 
0
$string="cari naskah dengan edisi tahun 2017"; 
    $stopwords = array("dan", "dengan"); 
     $jumlah_count = 0; 
     $jumlah = count(explode(' ',$string)); 
     echo "<table border='1'>"; 
     echo "<tr><th>Kata</th></tr>"; 
     for ($i=0; $i <$jumlah; $i++) 
     { 

      if(!in_array($word[$i],$stopwords)){  
      echo "<tr><td>"; 
      echo "word $jumlah_count = $word[$i]"; 
      echo "</td></tr>"; 
       $jumlah_count++;        
      } 
     } 
     echo "</table>"; 
     echo "<b>Number of words : " .$jumlah_count. "</b><br>"; 
     echo "<br />"; 
相關問題