duanpengya7074
duanpengya7074
2016-06-25 01:10

在替换文本中的内容时无限循环[重复]

已采纳

I'm new to PHP and try to implement some stuff on my own without using all built-in PHP functions. Here I want to simply search and replace stuff in my text as str_replace() does it. Except I try to do it without that function.

Right now I have this code:

<?php

$offset = 0;

parse_str(file_get_contents("php://input"), $_POST);
if (isset($_POST['text'])&&isset($_POST['search'])&&isset($_POST['replace'])) {
     $text = $_POST['text'];
     $search = $_POST['search'];
     $replace = $_POST['replace'];
     $search_len = strlen($search);
     $strpos = strpos($text,$search,$offset);
        while ($strpos<=strlen($text)){
            $offset = $strpos + $search_len;
            $text = substr_replace($text,$replace,$strpos,$search_len);//line 15
            $strpos = strpos($text,$search,$offset);
 }
  echo $text;

 } ?>

<hr>
<form action="new.php" method="POST" name="form">
  <textarea name="text" rows="6" cols="30" ></textarea><br><br>
  search  <br><br>
  <input type="text" name="search" ><br><br>
  replace<br><br>
  <input type="text" name="replace" ><br><br>
  <input type="submit" value="Submit"><br><br>
</form>

But for some reason my while loop falls into an infinite loop and the scripts ends with an error.

Error:

Fatal error: Maximum execution time of 30 seconds exceeded in C:\Users\Piyush\PhpstormProjects\untitled ew.php on line 15

I fail to see why, where and how my while loop falls into an infinite loop?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drmlxgmqn18198265 drmlxgmqn18198265 5年前

    Just use str_replace, Don't go against the grain.

    http://php.net/manual/en/function.str-replace.php

    str_replace — Replace all occurrences of the search string with the replacement string

    <?php
    
    parse_str(file_get_contents("php://input"), $_POST);
    if (isset($_POST['text'])&&isset($_POST['search'])&&isset($_POST['replace'])) {
         $text = $_POST['text'];
         $search = $_POST['search'];
         $replace = $_POST['replace'];
         $text = str_replace($search, $replace, $text);
         echo $text;
    
    } 
    ?>
    
    <hr>
    <form action="new.php" method="POST" name="form">
      <textarea name="text" rows="6" cols="30" ></textarea><br><br>
      search  <br><br>
      <input type="text" name="search" ><br><br>
      replace<br><br>
      <input type="text" name="replace" ><br><br>
      <input type="submit" value="Submit"><br><br>
    </form>
    
    点赞 评论 复制链接分享

为你推荐