Nalmelune
Nalmelune

Reputation: 88

php replacing between two tags in file html

I have a file.html with text like this

<h1 id="content1">Hello!</h1>

I have a form like this

<form method="POST"><textarea name="content1"></textarea></form>

and confirm button below this. What i need is to replace text between tags in html file with text in form. The code i've already got:

<? if ( isset ($_POST['submit']) ) 
{
$handle = fopen("file.html", "c+");
if ($handle)
 {
 if (isset($_POST['content1'])
 {
   stream_get_line($handle, 4096, '"content1">');
   $stringtoreplace = stream_get_line($handle, 4096, '</h1>');
   *INSERT REPLACEMENT CODE HERE*
 }
 fclose($handle);
 }
}
?>

Help with it please...


Got it! Thank you all for answers. There is working code:

<?if ( isset ($_POST['submit']) ) 
{
$handle = fopen("file.html", "c+");
if ($handle)
 if ( isset ($_POST['content1']) ) 
 {
 stream_get_line($handle, 4096, '"content1">');
 $stringtoreplace=stream_get_line($handle, 4096, '</h1>');
 fclose($handle); //getting string between <h1 id="content1"> and </h1>
 $file = 'file.html';
 $contents = file_get_contents($file);
 $contents = str_replace($stringtoreplace,$_POST['content1'],$contents);
 file_put_contents($file,$contents); //rewriting file with new string
 }
}
?>

Upvotes: 0

Views: 1251

Answers (3)

Rafael Soufraz
Rafael Soufraz

Reputation: 964

For me, this seems good:

<?php if ( isset ($_POST) ) 
{
    $find = $_POST['find'];
    $replace = $_POST['replace'];
    $file = 'test.txt';
    $contents = file_get_contents($file);
    $contents = str_replace($find,$replace,$contents);
    file_put_contents($file,$contents);
}
?>

<form method="POST" action="index.php">
    <input name="find" placeholder="Path to find" value="">
    <input name="replace" placeholder="Path to replace" value="">
    <input type="submit" value="Go">
</form>

I hope that it works to you.

Upvotes: 1

aksu
aksu

Reputation: 5235

Use simply str_replace from php.

 if (isset($_POST['content1'])
 {
   stream_get_line($handle, 4096, '"content1">');
   $stringtoreplace = stream_get_line($handle, 4096, '</h1>');
   $string = str_replace($stringtoreplace, $_POST['content1'], fread($link, filesize('file.html')));
 }

Upvotes: 0

Jorge Barata
Jorge Barata

Reputation: 2317

why don't you use PHP instead a simple html file?

//file.php
<h1 id="content1"><?php echo $content1 ?></h1>

//main.php
<?php
if (isset($_POST['content1']) {
  $content1 = $_POST['content1'];
  include 'file.php';
}

Upvotes: 0

Related Questions