简体   繁体   中英

while loop doesn't work properly,why?

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>

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 {

You did a mistake { :

while ($strpos=strpos($text,$search,$offset)) {

So :

<?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)) { // You forgetten the {
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM