preg_match_all 使用 $row 计算匹配词

preg_match_all count match word using $row

我想使用 $row 查找字符串中的单词数,但我不知道如何。

在这个变量里面 $row['item_name']:

IphoneAsus Strix LaptopIphoneBagIphoneCalculatorMakeupIphoneWalletIphone

我正在使用此代码:

<?php 
error_reporting(0);
?>

<html>
<head>
    <title></title>
</head>
<body>
    <table>
        <tr>
            <th>ID</th>
            <th>Item Name</th>
            <th>Type</th>
            <th>Brand</th>
            <th>Model</th>
            <th>Color</th>
            <th>Status</th>
        </tr>
        <?php 

        $db = mysqli_connect("localhost","root","","matching");

        $sql = "SELECT * FROM item";

        $result = mysqli_query($db, $sql) or die ("Invalid Query: $sql");

        if ($result->num_rows > 0) 
        {
            while($row = $result->fetch_assoc()) 
            {
                echo "<tr>
                <td align='center'>" . $row["id"] . "</td>
                <td align='center'>" . $row['item_name'] . "</td>
                <td align='center'>" . $row['sub1_type'] . "</td>
                <td align='center'>" . $row['sub2_brand'] . "</td>
                <td align='center'>" . $row['sub3_model'] . "</td>
                <td align='center'>" . $row['sub4_color'] . "</td>
                <td align='center'>" . $row['status'] . "</td>
                </tr>";

                //inside this $row['item_name']: Iphone, Asus Strix Laptop, Iphone, Bag, Iphone, Calculator, Makeup, Iphone, Wallet, Iphone

                echo $number = preg_match_all('/Iphone/', $row['item_name']);
                // output:1010100101
            }
        }

        ?>
</table><br><br>
    <?php
    $a="IphoneAsus Strix LaptopIphoneBagIphoneCalculatorMakeupIphoneWalletIphone";    
    echo $number = preg_match_all('/Iphone/', $a); //ouput:5  
    ?>

</body>
</html>

输出应该是:5

但是输出显示:1010100101

有人知道吗?

谢谢!

据我了解,$row['item_name'] 不包含 IphoneAsus Strix LaptopIphoneBagIphoneCalculatorMakeupIphoneWalletIphone 但每行包含:

  1. Iphone --> 1 场比赛
  2. Asus Strix Laptop --> 0 匹配
  3. Iphone --> 1 场比赛
  4. Bag --> 0 匹配
  5. Iphone --> 1 场比赛

...

所以你的 10 行有 1010100101

查看生成页面的来源,您没有 1010100101,而是 1 然后 0 然后 1 然后 0。 .. 在 <tr>...</tr>

之间

我建议你换行:

echo $number = preg_match_all('/Iphone/', $row['item_name']);

与:

$number += preg_match_all('/Iphone/', $row['item_name']);

然后在 while 循环之后:

echo $number; 

这里你会得到 5 如预期的那样。