获取文件内容并更改一行,然后使用PHP

时间:2016-04-18 19:23:15

标签: php

我目前正在做的似乎是尝试工作,但是,它无法正常保存。

我正在尝试获取文件的内容,根据用户输入字段重写一行(这只是一个用于测试的虚拟页面),然后保存新文件。但是,它不会替换内容。

$newtext = $_POST['info'];
$txt = 'text.txt';
$h1 = `\<h1 `
$read_txt = file_get_contents($txt);
$add_new = $h1 . $newtext;
$new = preg_replace("'/".$h1."/'", $add_new, $read_txt);
file_put_contents($txt, $new);

那么这应该做的是用<h1替换text.txt中的文本<h1 class="added"。正如我之前所说,这只是替换的测试(我将class="added"放在表单中)。但是,它没有这样做,我不确定为什么。

2 个答案:

答案 0 :(得分:1)

对于简单的字符串替换,您可以使用 .tile { width: 100%; display: inline-block; box-sizing: border-box; background: #fff; padding: 20px; margin-bottom: 30px; height: 135px; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; } .hideText { height: 0; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; overflow: hidden; } .title:hover .hideText{ height: 260px !important; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; display: block; }

http://php.net/manual/it/function.str-replace.php

<div class="col-sm-3"> <div class="tile blue"> <a href="#" style="color: black; text-decoration: none;"> <div class="title" > <h3 style="font-size: 30px !important;"><span class="glyphicon glyphicon-pencil" style="padding-right: 10px;"></span>Is something broken?</h3> <hr /> <p style="font-size: 19px !important;"><span class="glyphicon glyphicon-info-sign" style="padding-right: 10px;"></span>Hover to view details</p> <p class="hideText">The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</p> </div> </a> </div> </div> </div>的instaead(在你的代码中不起作用,因为 - 我很确定 - 正则表达式格式错误)。

str_replace

答案 1 :(得分:0)

对正则表达式进行修正,如下所示:
$1 编号引用第一个捕获的子模式

...
$add_new = $newtext;
$new = preg_replace("/(\<h1)/", "$1".$add_new, $read_txt);
...