如何在下面提到的代码中用PHP脚本替换文本区域的内容

时间:2012-02-28 10:36:19

标签: php

我有2个文本框和1个文本区域 用户将通过搜索框搜索内容 并提供应该被替换的词。

Scenerio 1:

我想用“坏”字替换“好”字 但是此代码不会替换文本区域内容。 它更适用于新替换的字符串

解决方案是什么?

<body>

<form id="form1" name="form1" method="post" action="">

<p>
<label for="search">Search :</label>
<input type="text" name="search" id="search" />
</p>

<p>
<label for="replace">Replace</label>
<input type="text" name="replace" id="replace" />
</p>

<p><Br />
<input type="submit" name="submit" id="submit" value="Submit" />
<label for="textarea"></label>
</p>

<p><br />
<textarea name="textarea" id="textarea" cols="45" rows="5"  >
"Good morning how are you today are you feeling Good.";
<?php

if(isset($_POST["submit"]))
{
     $search = $_POST["search"];
 $replace = $_POST["replace"];
 $textarea = $_POST["textarea"];

 $newtext = str_replace($search,$replace,$textarea);
     echo $newtext;

}

?>
   </textarea>
  </p>
</form>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

您需要在PHP中使用条件语句来控制是否显示默认文本。目前你只是在它之后添加动态文本。

<textarea name="textarea" id="textarea" cols="45" rows="5"  >
    <?php
        if(isset($_POST["submit"])) {
            $search = $_POST["search"];
            $replace = $_POST["replace"];
            $textarea = $_POST["textarea"];

            $newtext = str_replace($search,$replace,$textarea);
            echo $newtext;
        } else {
            echo "Good morning how are you today are you feeling Good.";
        }
    ?>
</textarea>

答案 1 :(得分:0)

HTML脚本

<html>
<body>
<form action="srch.php" method="post">
Find: <input type="text" name="find" value=><br><br>
Replace: <input type="text" name="replace" ><br><br>
<input type="submit" value="Replace"/><br><br>

<textarea name="maintext" rows="8" cols="80"></textarea>
</form>
</body>
</html>

php脚本.......

<html>
<body>

<?php
$find= $_POST['find'];
$replace= $_POST['replace'];
$text= $_POST['maintext'];
if (isset($find) && isset($replace))
{
$newtext= str_replace($find, $replace, $text);
}
?> 
<form action="" method="post">
Find: <input type="text" name="find" value='<?php echo $find; ?>'/><br><br>
Replace: <input type="text" name="replace" value='<?php echo $replace; ?>'/><br><br>
<input type="submit" value="Replace"/><br><br>

<textarea name="maintext" rows="8" cols="80"><?php echo $newtext; ?></textarea>
</form>

</body>
</html>