How would I go about appending a character to the end of every line except for the last line? The script won't know the length of the variable, as the last ten lines are loaded via tail.

Thanks!

Dani AI

Generated

As asked for appending a character to every line except the last, and following ’s split/implode idea, the main pitfalls to cover are mixed line endings (CRLF vs LF), trailing newline(s) and empty lines. The snippet below normalizes line endings, preserves whether the original had a trailing newline, and appends the character to every textual line except the final one.

<?php
$char = ';';                    // character to append
$text = $inputFromTail;         // original text

// normalize CRLF -> LF
$norm = str_replace(["\r\n", "\r"], "\n", $text);

// remember if original ended with a newline
$had_trailing_newline = substr($norm, -1) === "\n";

// remove trailing newline(s) so "last line" means last textual line
$trimmed = rtrim($norm, "\n");

// split and append to every line except the last textual line
$lines = explode("\n", $trimmed);
$last = count($lines) - 1;
for ($i = 0; $i < $last; $i++) {
    $lines[$i] .= $char;
}

// rejoin and restore a single trailing newline if the original had one
$result = implode("\n", $lines);
if ($had_trailing_newline) {
    $result .= "\n";
}

Notes: if the requirement is to treat the last non-empty line as the final line (skip appending to trailing blank lines), walk the array from the end to find the last non-empty element and use that index as $last. If the intent is "append to every line that has a newline after it" a compact regex alternative is preg_replace('/(.+)(\r?\n)/', '$1'.$char.'$2', $text) — that appends only to lines terminated by a newline and therefore leaves a final non-newline-terminated line untouched. The explode/rtrim approach is clearer and safer for mixed endings and when preserving original trailing-newline behavior matters.

In php we can use explode function, in that use "\n" as delimeter.
It will give you array of lines, traverse through each element and append the character you want to append except the last element of the array.
Now impload array using implode function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.