douli4337 2018-05-10 15:42
浏览 139
已采纳

为数组中的每个索引添加+1

I have a form that takes in a users input and puts it in an array, the user then chooses a word they want to find in said array. Thereafter the array is checked to see what each index of the word is as well as each occurrence of the word in the text.

So if you write the string "What is what" and want to find the word "what" it will say that the position of the word is "0 and 2" whereas I'd like it to say "1 and 3". How do I go about this?

Here's the code:

 <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'])){
    $parts = explode(" ", $_POST['textarea']);
    $strName = $_POST['search'];
    print_r ($parts);
    echo '<br>';
    foreach($parts as $item) {
        if ($item == $strName) {
            $counter++;
        }

    }
    echo "The word $strName can be found at: ";
    echo implode(' ', array_keys($parts, $strName));    
    echo "<br>";
    echo "The word $strName was found $counter times";
    }
  • 写回答

3条回答 默认 最新

  • doudao3170 2018-05-10 15:52
    关注

    I'm not sure what you're doing with the foreach or if that's where you want to create the positions, but:

    foreach($parts as $pos => $item) {
        if ($item == $strName) {
            $result[] = $pos + 1;
        }
    }
    

    Then just:

    echo implode(' ', $result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器