2015-08-15 40 views
2
<?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> 

如果要替换的单词的第一个字或词只在字符串中那么它不工作,但如果要替换的单词在除了第一个之外的任何其他位置,那么它工作正常。为什么这个PHP substr_replace()不替换第一个字

回答

0

您可以使用下面PHP函数str_replace,容易

实现它的语法

str_replace(find,replace,string,count) 

找到 - >它需要field.Specifies价值发现

更换 - >这是必填字段。指定要替换的值取值为

- >它需要field.Specifies要搜索

计数字符串 - >据计数更换的次数可选field.A变量

1

strpos返回的位置针($search)在干草堆($text)中找到。如果在它的开头找到它,strpos将返回0,PHP将其视为false,并因此终止while循环,甚至不输入它。要解决这个问题的方法之一是使用!==运营商布尔FALSE和整数0区分:

while (!($stringpos = strpos($text, $search, $offset)) !== FALSE) 
0

你应该使用while循环做,因为它会至少执行一次,但你需要做的在第一个if语句中变量就像这样

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