为什么这个php substr_replace()不';不要替换第一个单词 搜索: 替换为:
如果要替换的单词是字符串中的第一个单词或唯一一个单词,则它不起作用,但如果要替换的单词位于除第一个之外的任何其他位置,则它工作正常。您可以使用下面的php函数为什么这个php substr_replace()不';不要替换第一个单词 搜索: 替换为:,php,string,strpos,Php,String,Strpos,如果要替换的单词是字符串中的第一个单词或唯一一个单词,则它不起作用,但如果要替换的单词位于除第一个之外的任何其他位置,则它工作正常。您可以使用下面的php函数stru replace,并轻松实现它 语法 <?php $offset =0; if (isset ($_POST['text']) && isset($_POST['searchfor'])&&isset($_POST['replacewith'])) { $text = $_POST['tex
stru replace
,并轻松实现它
语法
<?php
$offset =0;
if (isset ($_POST['text']) && isset($_POST['searchfor'])&&isset($_POST['replacewith']))
{
$text = $_POST['text'];
$search = $_POST['searchfor'];
$replace = $_POST['replacewith'];
$length = strlen($search);
if (!empty($_POST['text'])&& !empty($_POST['searchfor'])&&!empty($_POST['replacewith']))
{
while ($stringpos = strpos($text, $search, $offset))
{
$offset = $stringpos + $length;
$text = substr_replace($text, $replace, $stringpos, $length);
}
echo $text;
}
else
{
echo 'Please fill in all the fields';
}
}
?>
<form action=53fineandreplace.php method="POST">
<textarea name = "text" rows="6" cols = "30"></textarea><br><br>
Search For:<br>
<input type= "text" name = "searchfor"><br><br>
Replace with:<br>
<input type="text" name = "replacewith"><br><br>
<input type = "submit" value = "Submit">
</form>
查找->它是必填字段。指定要查找的值
替换->它是必填字段。指定要替换查找中的值的值
字符串->它是必填字段。指定要搜索的字符串
计数->这是可选字段。一个计算替换次数的变量返回指针(
$search
)在草堆中的位置($text
)。若在它的开头找到它,strpos
将返回0
,PHP将其视为false
,从而在时终止循环,甚至不输入它。解决这个问题的一种方法是使用==
运算符,用于区分布尔值FALSE
和整数0
:
str_replace(find,replace,string,count)
您应该只使用do while循环,因为它将至少执行一次,但您需要在第一个if语句中使用如下所示的变量
while (!($stringpos = strpos($text, $search, $offset)) !== FALSE)
if (isset($_POST['text']) && isset($_POST['replace_what']) && isset($_POST['replace_with'])){
$text=$_POST['text'];
$search=$_POST['replace_what'];
$replace=$_POST['replace_with'];
$string_length=strlen($search);
$offset=0;
$strpos=0;
if (!empty($text) && !empty($search) && !empty($replace)) {
do{
$offset= $strpos + $string_length;
$text=substr_replace($text,$replace,$strpos,$string_length);
}while ($strpos= strpos($text,$search,$offset));