使用PHP替换txt文件中的一些空白
我是PHP的新手 我想用一些使用PHP的单词替换txt.file中的一些空白。 此my.txt文件(text.txt): 这就是我想要的使用PHP替换txt文件中的一些空白,php,string,replace,aiml,Php,String,Replace,Aiml,我是PHP的新手 我想用一些使用PHP的单词替换txt.file中的一些空白。 此my.txt文件(text.txt): 这就是我想要的 A chatbot record <category> <pattern>Hello, how are you?</pattern> <template>I'm Fine</template> </category> 聊天机器人记录 你好,你好吗? 我很好 我已经用str\u repl
A chatbot record
<category>
<pattern>Hello, how are you?</pattern>
<template>I'm Fine</template>
</category>
聊天机器人记录
你好,你好吗?
我很好
我已经用str\u replace(“,”,“\n”)
尝试了一些PHP代码,但它不起作用,我该怎么办
我的实验失败了:
<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace(" ", "<category><pattern>", "\n"); //I know it's wrong in here, please help me to fix it!
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>
您可能应该这样做:
<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace(" ", "<category><pattern>", $myfile);
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>
如果您仍然有问题,可能是因为您的文件不包含,或者您正在查找\n(新行字符)
问题是您没有替换文件中的字符串,而是替换了字符串“\n”中的“”。Regex可能是解决此问题的方法
<?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>$2</pattern>\n<template>$3</template>\n</category>", $string);
file_put_contents("text.txt", $replaced);
是否总是有3行(和空行)?不应该有标记吗?看看使用正则表达式,然后改为使用。@IvoP感谢您提醒我\W
包含\n
,[\n\W]
与\W
相同,我尝试过这个,但看起来它不会改变我文本中的任何内容。txt@RonAshrovy您只需使用file\u put\u contents
将内容放回文件,更新了答案。谢谢@apokryfos,我真的想把一个大的text.txt文件转换成aiml,有没有什么循环或者简单的东西?谢谢,我已经尝试过了,但是它不起作用,我的文本文件没有改变,而是使用了fopen
tryfile\u get\u contents
函数,然后在最后使用file\u put\u contents('text.txt',$yourString,file\u APPEND | LOCK\u EX)代码>
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(" ", "<category><pattern>", $myfile);
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>
<?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);
?>
<?php
$string = 'A Chatbot record
Hello, how are you?
I\'m Fine';
$reg = '#^(.*\n)\n(.*)\n\n(.*)#';
$replace = '$1<category>
<pattern>$2</pattern>
<template>$3</template>';
echo preg_replace($reg, $replace, $string);
<?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>$2</pattern>\n<template>$3</template>\n</category>", $string);
file_put_contents("text.txt", $replaced);