0

i need to find a line and change it to whatever user will type in input i didnt write this code pls help

<?php
$myfile = 'test.txt';
$lines = file($myFile, FILE_IGNORE_NEW_LINES);
$lines[4] = $_POST['title'];
file_put_contents($myFile , implode("\n", $lines));
?>

i tryed lot of ways but non of them works and i only have this code . i am working on project idea is simple user will give type url of website i need to find a line and change it to <form action="process.php" method="post"> i need help its will be on same line so i dont need to change line i searched lot of ways but does not works for me. i am starter at php so...

1
  • Typo: $myfile vs $myFile Commented Mar 19, 2021 at 7:34

1 Answer 1

3

There is an error in your code.

$lines = file($myFile, FILE_IGNORE_NEW_LINES);

should be

$lines = file($myfile, FILE_IGNORE_NEW_LINES);

because you're declaring $myfile = 'test.txt';

Note the usage of smaller case f in file name.

Now, coming to your question.

You want to replace some lines in the file with user input.

Let's assume that you want to replace the text THIS SHOULD BE REPLACED. For that, you could use the code something line below:

<?PHP
$myfile = './test.txt';
$lines = file($myfile, FILE_IGNORE_NEW_LINES);

$textToBeReplaced = "THIS SHOULD BE REPLACED";

$index = array_search($textToBeReplaced, $lines);
if (false !== $index) {
    $lines[$index] = $_POST['title'] ?? '';
}
file_put_contents($myFile , implode("\n", $lines));
?>
 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.