You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP表单查询:如何将数组中匹配单词的索引值各加1?

Solution to Adjust Index Positions to 1-Based

Let's fix your code to return 1-based indices instead of 0-based, and also handle a couple of edge cases like case-insensitive matching (since your example shows "What" and "what" being treated as matches) and extra spaces in the input.

Here's the modified code with explanations:

<form action="sida3.php" method="post">
    Text: <textarea name="textarea"></textarea> <br>
    Search word: <input type="text" name="search"> <br>
    <input type="submit" name="submit" value="Submit">
</form>

<?php
if(isset($_POST['submit'])){
    // Split input text into words, filter out empty strings from extra spaces
    // and reindex to avoid gaps in indices
    $parts = explode(" ", $_POST['textarea']);
    $parts = array_values(array_filter($parts, function($item) {
        return trim($item) !== '';
    }));
    
    $searchWord = $_POST['search'];
    print_r($parts);
    echo '<br>';
    
    $positions = [];
    
    // Loop through each word with its original index
    foreach($parts as $index => $word) {
        // Case-insensitive comparison to match "What" and "what"
        if(strcasecmp(trim($word), trim($searchWord)) === 0) {
            // Convert 0-based index to 1-based by adding 1
            $positions[] = $index + 1;
        }
    }
    
    $matchCount = count($positions);
    
    echo "The word '$searchWord' can be found at: ";
    echo implode(' ', $positions);
    echo "<br>";
    echo "The word '$searchWord' was found $matchCount times";
}
?>

Key Changes Made:

  • 1-Based Indices: We take the original 0-based index from the loop and add 1 to it before storing it in the $positions array.
  • Case-Insensitive Matching: Using strcasecmp() instead of == ensures that uppercase and lowercase variations of the search word are both recognized, which aligns with your example.
  • Handle Extra Spaces: The array_filter() and array_values() combo removes empty strings created by multiple spaces in the input and reindexes the array so indices stay consecutive.
  • Simplified Count: Instead of looping twice to count matches, we use count($positions) since we're already collecting all matching positions.

Testing this with your example input "What is what" and search word "what" will now return positions 1 and 3 and a count of 2, exactly what you wanted.

内容的提问来源于stack exchange,提问作者 Matt J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:02:56