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
$positionsarray. - 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()andarray_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
相关产品推荐
相关产品推荐

