所以这个问题适用于很多语言,所以不要被我在终端中使用PHP的事实所抛弃。回答说Python或Perl可能也会提供我需要知道的内容。
所以我正在阅读一个文本文件,我想知道每行包含哪些特殊字符。例如,如果文本文件是这样的:
hello
world
我希望脚本输出"hello\nworld"
。我的根本问题是我正在尝试编写一个PHP脚本,其中涉及从文本文件中读取,但我希望它忽略空白行,但无论我尝试它还是读取空白行。我认为这是因为我没有为该线进行正确的匹配,所以我试图找出一条空行是如何存在的,我不确定它是"\n" or "\t\t"
等。
答案 0 :(得分:1)
像这样做普通的str_replace()
:
$text = str_replace( array("\n","\r"), array('\n', '\r'), $text);
答案 1 :(得分:0)
我的解决方案,当然更乏味,将删除空行,CLI PHP脚本需要Shebang在头部:
#!/usr/bin/php
<?php
//
// main test:
//
$xarr = file("MyFilename.txt");
$n = count($xarr);
$strret = "";
for($i = 0; $i < $n; $i++)
{
//
// ignore blank lines:
//
if(! preg_match("/^$/", $xarr[$i]))
{
if($i > 0)
{
$strret .= "\\n";
}
$strret .= rtrim($xarr[$i]);
}
}
//
echo $strret . "\n";
?>
使用文本文件:
# cat MyFilename.txt
hello
world
它说:
hello\nworld
答案 2 :(得分:-1)
我假设“特殊字符”只表示 \n
,\t
和\r
。
文字档案
hello
world
foo
bar!
baz_
<强> PHP:强>
$fp = fopen('textfile.txt', 'r');
while (!feof($fp)) {
$c = fgetc($fp);
if ($c == "\n") $c = '\n';
else if ($c == "\t") $c = '\t';
else if ($c == "\r") $c = '\r';
echo $c;
}
上面的脚本将基本上执行的操作是读取文件的每个字符,并替换它找到的\t
,\r
或\n
的任何匹配项。这消除了检查双重字符的必要性。