Skip to content

Instantly share code, notes, and snippets.

@podlom
Created October 4, 2023 15:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podlom/4713007194c2df7edd447b26d1c97d29 to your computer and use it in GitHub Desktop.
Save podlom/4713007194c2df7edd447b26d1c97d29 to your computer and use it in GitHub Desktop.
Break lines on two equal parts not breaking whole words
<?php
// Check if the input file exists
$inputFile = "_input_file_name.txt";
// Function to break a line into two parts, aiming for equal number of characters, without breaking words
function breakLineEqually($line) {
$length = strlen($line);
$mid = intdiv($length, 2);
$spaceBefore = strrpos($line, ' ', $mid - $length);
$spaceAfter = strpos($line, ' ', $mid);
if ($spaceBefore === false && $spaceAfter === false) {
// No spaces in the string
return [$line, ''];
}
if ($spaceBefore === false) {
$breakPoint = $spaceAfter;
} elseif ($spaceAfter === false) {
$breakPoint = $spaceBefore;
} else {
// Choose the closest space to the middle
$breakPoint = ($mid - $spaceBefore < $spaceAfter - $mid) ? $spaceBefore : $spaceAfter;
}
$part1 = trim(substr($line, 0, $breakPoint));
$part2 = trim(substr($line, $breakPoint));
return [$part1, $part2];
}
if (!file_exists($inputFile)) {
echo "The file input.txt does not exist.\n";
exit(1);
}
// Read the file line by line
$lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
echo "An error occurred while reading the file.\n";
exit(1);
}
// Process each line
foreach ($lines as $line) {
list($part1, $part2) = breakLineEqually($line);
echo $part1 . "\t" . $part2 . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment