2011-03-13 194 views
0

我有这样值的.txt文件的列表:PHP正则表达式question..adding逗号

aaa 
bbbb 
ddd 
eeeee 

我怎么会附加一个逗号和对所有这些结束,这样一个空间列表中查找此

aaa, 
bbbb, 
ddd, 
eeeee, 

感谢

+0

为什么要费心正则表达式?只需将该文件逐行读入一个字符串中,再附加一个逗号和一个空格,然后依次将每行写回。 – Amber 2011-03-13 05:09:42

回答

4

无需正则表达式等。只是get所有从你的文件中的文本,做一个好醇” str_replace()put回:

$contents = file_get_contents("myfile.txt"); 
$contents = str_replace("\n", ",\n", $contents); 
file_put_contents("myfile.txt", $contents); 

这不会插入逗号,如果最后一行没有一个换行符,但如果你真的需要它在那里,这里是一个改进版本,与交易:

$contents = trim(file_get_contents("myfile.txt")); 
$contents = str_replace("\n", ",\n", $contents) . ","; 
file_put_contents("myfile.txt", $contents); 
3
str_replace ("\n", ",\n", $your_variable); 

str_replace将足够多的满足您的需求