使用 PHP 替换 txt 文件中的一些空白 space

Replace some blank space in txt file using PHP

我是 PHP 的新手。

我想用 PHP 替换 txt.file 中的空白 space。 这是我的 .txt 文件 (text.txt):

A Chatbot record

Hello, how are you?

I'm Fine

这就是我想要的

A chatbot record
<category>
<pattern>Hello, how are you?</pattern>
<template>I'm Fine</template>
</category>

我已经用 str_replace("&nbsp;","<category><pattern>","\n") 尝试了一些代码 PHP,但它不起作用,我该怎么办?

我的实验失败了:

<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace("&nbsp;", "<category><pattern>", "\n"); //I know it's wrong in here, please help me to fix it!
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>

Thank you, and sorry for my bad english

$string = 'A Chatbot record

Hello, how are you?

I\'m Fine';

$explode = preg_split("#\n\s*\n#Uis", $string);
echo $explode[0];
echo "<category>";
echo "<pattern>".$explode[1]."</pattern>";
echo "<template>".$explode[2]."</template>";
echo "</category>";

对我来说,最好的方法是将您的字符串拆分成一个数组,这样您以后可以更轻松地工作。这是数组感谢 preg_split :

array(3) {
  [0] =>
  string(16) "A Chatbot record"
  [1] =>
  string(19) "Hello, how are you?"
  [2] =>
  string(8) "I'm Fine"
}

你可能应该这样做:

<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace("&nbsp;", "<category><pattern>", $myfile);
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>

如果您仍然遇到问题,可能是因为您的文件不包含 ,也许您正在寻找 \n(换行符)。

<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace("\n", "<category><pattern>", $myfile);
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>

问题是您没有替换文件中的字符串,而是替换了字符串“\n”中的“ ”。

<?php
$string = 'A Chatbot record

Hello, how are you?

I\'m Fine';

$reg = '#^(.*\n)\n(.*)\n\n(.*)#';
$replace = '<category>
  <pattern></pattern>
  <template></template>';

echo preg_replace($reg, $replace, $string);

正则表达式比分解或 strpos 解决方案更灵活。 (注:这里还是不见了。

问题仍然存在,是否所有文本总是在 1 行上

正则表达式可能是去这里的方式。

<?php
$string = file_get_contents("text.txt");

$replaced = preg_replace("/A Chatbot record(\W+)([^\n]+)\W+([^\n]+)/mi", "A chatbot record\n<category>\n<pattern></pattern>\n<template></template>\n</category>", $string);
file_put_contents("text.txt", $replaced);

这可以匹配所有模式

http://sandbox.onlinephpfunctions.com/code/95184665ec627cd9354d67853bb696865d51a03d