Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么我的查找和替换脚本总是适用于0位置之后的所有内容?_Php_Replace_Find_Str Replace - Fatal编程技术网

Php 为什么我的查找和替换脚本总是适用于0位置之后的所有内容?

Php 为什么我的查找和替换脚本总是适用于0位置之后的所有内容?,php,replace,find,str-replace,Php,Replace,Find,Str Replace,我正在学习PHP,我制作了一个简单的查找和替换脚本,但它似乎只适用于字符串中0位置之后的字符 以下是脚本: <?php $offset= 0; if( isset ($_POST['text']) && isset($_POST['search']) && isset($_POST['replace']) ){ $text = $_POST['text']; $search = $_POST['search']; $replace

我正在学习PHP,我制作了一个简单的查找和替换脚本,但它似乎只适用于字符串中0位置之后的字符

以下是脚本:

 <?php

 $offset= 0;

 if( isset ($_POST['text']) && isset($_POST['search']) && isset($_POST['replace'])   ){


 $text = $_POST['text'];
  $search = $_POST['search'];
  $replace = $_POST['replace'];

  $searchlength = strlen($search);



   if (!empty($text) && !empty($search) && !empty($replace)){

  while ($strpos = strpos($text, $search, $offset)) {
        echo$strpos;
        $text = substr_replace($text, $replace, $strpos, $searchlength);
        $offset = $strpos+$searchlength;
    }
   echo$text;

    }else{

echo'Please fill in something';
   }


 }




  ?>
 <hr>
 <form action= "index.php" method = "POST">

<textarea name= 'text' rows= '20' cols = '20'></textarea><br>
Search for:<br>
<input type='text' name ='search'><br>
Replace with:<br>
<input type='text' name ='replace'><br>
<input type='submit' value='find and replace'>

  </form>



搜索:

替换为:

无论我做什么,我都不能替换字符串中的第一个字符或第一个单词

while ($strpos = strpos($text, $search, $offset)) {
应该是

while (FALSE !== ($strpos = strpos($text, $search, $offset))) {
对于第一个字符,
$strpos
等于0,因此
while
循环永远不会启动