【问题标题】:Replace certain content in txt file and save it using PHP?替换txt文件中的某些内容并使用PHP保存?
【发布时间】:2013-08-29 19:15:35
【问题描述】:

所以我在 txt 文件的某个区域收到变量替换它并将其保存回来。我得到页码,并根据它得到分解的数据。无论如何,我会在下面发布一个代码以使其更清楚:

$pgnm = $_GET['page']; //This is the page number as I've said.

$conts = file_get_contents("content.txt");

content.txt 的内容如下所示:

text1|text2|text3

我在某些页面中显示此内容。例如在第一页上:text1,在第二个 text2 上,等等。

现在我正在制作一个成功更改这些内容的表单。我得到了我所说的页码和文字:

$text = "new text"; //this is the content which I want to be replaced instead of text2.

我将 content.txt 文件保存后如下所示:text1|new text|text2

让我们继续吧:

$exp = explode("|", $conts); //this explodes data into slashes. 

$rep = str_replace($exp[$pgnm], $text, $conts);

file_put_contents("content.txt", $rep); // Saving file

所有这些上述操作都可以完美运行,但现在这是我的问题。这仅在 content.txt 具有某些内容时才有效,如果它是空的,它会输入我的新文本,仅此而已:'新文本',仅此而已。也许我想添加第二页内容“新文本2”,在我完成输入并保存后,我希望文件显示如下:新文本|新文本2。如果 content.txt 的内容如下所示:'new text|' str_replace 不替换空字符串。所以这也是我的另一个问题。

我尝试了所有方法,但无法解决这两个问题。提前感谢您的帮助!

【问题讨论】:

  • 为什么不用数据库?

标签: php str-replace


【解决方案1】:

为什么不使用$exp 数组来构建内容。我的意思是$exp 包含所有块作为array() 一个接一个。因此,您只需更改或向数组添加新值(不需要str_replace())。然后使用implode('|',$exp);重建。

至于你的代码;

$exp = explode("|", $conts); //this explodes data into slashes. 
$exp[$pgnm] = $text;
file_put_contents("content.txt", implode('|',$exp)); // Saving file

【讨论】:

  • 我试试看。谢谢你的回答
【解决方案2】:

使用以下代码代替 str_replace:

$pgnm       = 1;
$text       = 'new text';
$conts      = 'text1||text3';
$exp        = explode('|', $conts); 
$exp[$pgnm] = $text;
$rep        = implode('|', $exp);
var_dump($rep); // string(20) "text1|new text|text3"

【讨论】:

  • 它返回:string(0) ""
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2011-04-04
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多