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);
How can I add a newline to the center position of each line?
//Related:
$wrapped = wordwrap($row, $width, '\N');
I'm not sure if this is what you're expecting, but it works given supplied text:
just some example text
some example text
example text
which results to a written file as: (if using ' '
)
just some
example
text
some
example
text
example
text
(EDIT) and as:
just some
example
text
some
example
text
example
text
(if using " "
) which will result having no spaces at the end of each line.
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 = "
"; // writes to file with no spaces at the end of each line
// $newline = '
'; // use single quotes if wanting to write
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);