Php 将换行符添加到文本文件行的中心长度位置
input.txtPhp 将换行符添加到文本文件行的中心长度位置,php,Php,input.txt just some example text, just some example text some example text example text, just some example text $inFile = "input.txt"; $outFile = "output.txt"; $data = array(); $ftm = fopen($outFile, "w+"); $fh = fopen($inFile, "r");
just some example text, just some example text
some example text
example text, just some example text
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row)/2;
$wrapped = wordwrap($row, $width);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
如何将换行符\n添加到每行的中心位置
//Related:
$wrapped = wordwrap($row, $width, '\N');
我不确定这是否是您所期望的,但考虑到提供的文本,它是有效的:
just some example text
some example text
example text
这将导致写入文件:(如果使用'\n'
)
(编辑)并作为:
(如果使用“\n”
),将导致每行末尾没有空格
PHP
你的意思是用\n
换行吗<代码>$wrapped=wrapp($row,$width,“\n”)
@bansi实际上我想在字符串中打印“\n”。我想这就是wordwrap
的作用。我想你从来没有测试过你的代码。它完全按照你说的做。@出于某种原因,如果它是小写,它就不会打印。你想在包装文本中输出文本\
和n
?然后'\n'
在wordwrap调用中,'
字符串不像“
引用字符串那样使用反斜杠字符。这非常接近。当我使用“\n”时,它会产生“一些示例文本”“出于某种原因。ie:不打印换行符。并且应该打印换行符的空白处丢失。请稍后打开文件本身。在我这边,有两条不同的线。我将用我得到的输出“在文件中”编辑我的答案@我的(编辑)和身份下的RRRFUSCOSE:@rrrfusco这就是我在文件本身中看到的。如果这个示例首先是用notepad++包装的word,那么在EOL中似乎有1个空格。当我运行此代码时,它会将\N添加到行的末尾。我已经尝试过rtrim来移除它,但这不起作用。关于如何删除尾随的任何想法\N。同样,中心应该保留。我看不出它如何在文件中“添加”一个\N
。如果您使用的是'\n'
而不是“\n”
是,则会在文件中添加\n
@rrrfusco
just some\nexample\ntext
some\nexample\ntext
example\ntext
just some
example
text
some
example
text
example
text
<?php
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$newline = "\n"; // writes to file with no spaces at the end of each line
// $newline = '\n'; // use single quotes if wanting to write \n in the file
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row) / 2;
$wrapped = wordwrap($row, $width, $newline);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);