замена php между двумя тегами в файле html

0

У меня есть файл.html с текстом, подобным этому

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

У меня есть такая форма

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

и подтвердите кнопку ниже этого. Мне нужно заменить текст между тегами в html файле текстом в форме. Код, который у меня уже есть:

<? 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);
 }
}
?>

Помогите с этим, пожалуйста...


Понял! Спасибо всем за ответы. Существует рабочий код:

<?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
 }
}
?>
  • 0
    Может быть найти заменить?
  • 0
    Вы можете использовать JavaScript 'innerhtml'? Установите новый код как PHP var $ innerhtml, тогда, если установлено значение $ innerhtml, у вас есть функция js, заменяющая содержимое html.
Показать ещё 1 комментарий
Теги:

3 ответа

0
Лучший ответ

Для меня это кажется хорошим:

<?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>

Я надеюсь, что это сработает.

  • 1
    Это помогло мне понять, как правильно переписать файл, спасибо!
0

почему бы вам не использовать PHP вместо простого html файла?

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

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

Используйте просто str_replace из 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')));
 }
  • 0
    Проблема здесь в том, что это не единственная строка во всем файле. Есть еще несколько строк до и после ... Будет ли это работать?
  • 0
    Да, @ Nalmelune
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню