1

I want to have a simple HTML input field where people can type all kinds of nonsense. For example, a user types: "Hello, I'm Nicky". When the user then clicks the button Send, I want a simple PHP script to replace the word "Nicky" to "Nicki" and show it to the user. So basially, just a simple PHP script which replaces specific words from an input field and then print out the exact same line the user has inputted, except show Nicki instead of Nicky.

How can I achieve this, in the most simplest way?

My code looks like this now:

<?php

$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']);

?>

<form method="post">
<input type="text" name="name">
<input type="submit">
</form>
1
  • str_replace("Nicky","Nicki",$_POST['name']); Commented Dec 21, 2016 at 14:27

1 Answer 1

1
<?php
 if(isset($_POST['form-action']) && $_POST['form-action'] == "submit-form"){ // form has been submitted
  echo "<p>BEFORE: ".$_POST['name']."</p>"; // what the user entered "Nicky"
  $_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']); // find/replace Nicky with Nicki
  echo "<p>AFTER: ".$_POST['name']."</p>"; // what the $_POST['name'] now is
 }
?>

<form method="post">
 <input type="text" name="name" value="Nicky">
 <input type="submit">
 <input type="hidden" name="form-action" value="submit-form">
</form>

In addition to this, if you want to expand the Find & Replace variables, you could use an array:

$FindReplace = array("Nicky"=>"Nicki", "Blue"=>"Red"); // build an array of find/replace variables
....
foreach($_POST as $Name=>$Value){
    echo "<p>Before: ".$Name."=".$Value."</p>"
    foreach($FindReplace as $Find=>$Replace){
        $Value = str_replace($Find,$Replace,$Value);
    }
    echo "<p>After: ".$Name."=".$Value."</p>"
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi, how would I incorporate this within my php file?
@Glenn without seeing your PHP file, it's a bit tricky to instruct. Show us your code.
Truth to be told, my PHP file is empty.. Haha.
Show us your HTML then.
Hi JustBaron, I edited my initial post with the code that I am currently using, but isn't working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.