我的代码如下: -
<?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 :(得分: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 />";
?>
答案 1 :(得分: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 />";