在文本文件行的中心长度位置添加换行符

时间:2014-03-18 03:49:04

标签: 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");      

$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');

1 个答案:

答案 0 :(得分:1)

我不确定这是否是您所期望的,但它在提供的文字中有效:

just some example text
some example text
example text

导致写入文件为:(如果使用'\n'

just some\nexample\ntext
some\nexample\ntext
example\ntext

编辑)和as:

just some
example
text
some
example
text
example
text

(如果使用"\n")将导致每行末尾没有空格。

PHP

<?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);