Php 为什么我的查找和替换脚本总是适用于0位置之后的所有内容?
我正在学习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
$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
循环永远不会启动