I’m working on a custom forum and need to enforce a maximum number of lines in user signatures. I initially tried using explode with \n but that didn’t work across all platforms. I ended up using nl2br() and then exploding by <br /> tags. That works, but it feels hacky.
Is there a cleaner, platform-independent way to count lines in user input? I’m looking for a robust solution that handles Windows (\r\n), Unix (\n), and old Mac (\r) line endings. Should I use something like preg_split() to handle all cases? Also, what’s the best practice for actually limiting the number of lines—should I truncate the string or show an error?
// Current approach:
$input = $_POST['signature'];
$withBreaks = nl2br($input);
$lines = explode('<br />', $withBreaks);
if (count($lines) > 5) {
echo 'Too many lines';
}
I’m using modern PHP (8.x) and want to keep it clean. Any suggestions?
Topic Summary: Counting lines in user signatures across platforms? Avoid hacky nl2br(). Use preg_split('/\R/', $input) to handle
Featured GitHub Resource:
- antlr/antlr4 - ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or … (★ 18956)
Video Tutorial:
Official Documentation & Reference Links:
---
title: Limit Signature Line Count
---
flowchart TD
A[Start] --> B[Retrieve user signature input]
B --> C[Split signature into lines]
C --> D[Count lines]
D --> E{Line count > limit?}
E -- Yes --> F[Truncate to allowed lines]
E -- No --> G[Accept signature]
F --> G
G --> H[Save signature to database]
H --> I[End]
Good question! Your approach with nl2br() is fragile because it also converts actual <br> tags in the input, and it’s not really counting lines—just break tags. A better solution is to use preg_split() with a regex that matches all common newline sequences.
Here’s a clean, modern PHP approach:
$input = $_POST['signature'] ?? '';
$maxLines = 5;
$lines = preg_split('/\r\n|\r|\n/', $input);
$lineCount = count($lines);
if ($lineCount > $maxLines) {
// Option 1: Reject with error
echo "Signature must not exceed $maxLines lines.";
} else {
// Option 2: Truncate silently (but show warning)
$truncated = implode("\n", array_slice($lines, 0, $maxLines));
}
This regex handles all line ending styles. Also, avoid using nl2br() for counting—it’s meant for display, not logic. For validation, always check before saving. If you need to preserve the original line endings for later output, store the raw input and use nl2br() only when rendering.
For a more defensive approach, you can also sanitize the input by removing trailing empty lines:
$lines = array_filter($lines, function($line) {
return trim($line) !== '';
});
But that might not be desired—some users intentionally have blank lines. Up to you!
Hope that helps!