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

时间:2015-02-20 10:27:34

标签: php html while-loop

它保持(回声)某事。

<?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 个答案:

答案 0 :(得分:2)

您忘记了while正文周围的括号:

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 {

如果没有这些括号,则在循环期间执行第一个命令(echo $strpos),在循环之后执行第二个echo

您的代码与以下内容相同:

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 :(得分:0)

你犯了一个错误{

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

所以:

<?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>
相关问题