doulian8742 2015-02-20 10:27
浏览 36
已采纳

while循环不能正常工作,为什么?

It keeps (echo)ing sth.

<?php
$offset=0;
if (isset( $_POST['text']) && isset( $_POST['search_for']) &&    isset($_POST['replace'])){
     $text= $_POST['text'];
     $replace= $_POST['replace'];
     $search= $_POST['search_for'];
     $string_length=strlen($search);
if (!empty ($text) && !empty($search) && !empty($replace)){
    while ($strpos=strpos($text,$search,$offset))
    echo $strpos.'<br>';
    echo $offset=$strpos+$string_length.'<br>';
    } else { 
     echo 'please fill all fields';
    }  
    }
    ?>
<form action='index.php' method ='POST'>
  <textarea name='text'  rows=6 cols=30 > </textarea><br><br>
   Search for:<br>
   <input type ='text' name='search_for'><br><br>
   Replace with:<br>
   <input type='text' name='replace'><br><br>
   <input type='submit' value='Find & Replace'>
</form>
  • 写回答

2条回答 默认 最新

  • douxian7808 2015-02-20 10:33
    关注

    You forgot brackets around the while body:

    if (!empty ($text) && !empty($search) && !empty($replace)) { // here
        while ($strpos=strpos($text,$search,$offset)) {
           echo $strpos.'<br>';
           echo $offset=$strpos+$string_length.'<br>';
        } // here
    } else {
    

    Without these brackets just first command is executed (echo $strpos) during the loop and after the loop the second echo is written.

    Your code was the same as:

    if (!empty ($text) && !empty($search) && !empty($replace)) { // here
        while ($strpos=strpos($text,$search,$offset)) {
           echo $strpos.'<br>';           
        } // here the while loop ends
    
        echo $offset=$strpos+$string_length.'<br>';
    } else {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程