留言板、評論區常需限制「行數」而非單純字數。PHP 內建無直接函式,需自行實作。
<?php
/**
* 計算字串中的換行數 (LF \n)
* @param string $text 輸入文字
* @return int 換行數 (行數 = 換行數 + 1)
*/
function countLines(string $text): int
{
// 統一換行符為 LF
$text = str_replace(["\r\n", "\r"], "\n", $text);
// 空字串視為 0 行 (或 1 行視業務定義)
if ($text === '') return 0;
// substr_count 計算子字串出現次數,效能最佳
return substr_count($text, "\n") + 1;
}
// 測試
$tests = [
'' => 0,
'單行' => 1,
"第一行\n第二行" => 2,
"行1\r\n行2\r行3\n" => 4, // 尾端換行算一行
"多行\n\n內容" => 3, // 空行也計算
];
foreach ($tests as $input => $expected) {
$result = countLines($input);
echo "輸入: " . json_encode($input) . " → 行數: $result " . ($result === $expected ? '✅' : '❌') . "\n";
}
<?php
/**
* 驗證並截斷超過最大行數的文字
* @param string $text 輸入文字
* @param int $maxLines 最大允許行數
* @param string $truncateSuffix 截斷後綴
* @return array ['valid' => bool, 'text' => string, 'lineCount' => int]
*/
function validateAndTruncateLines(string $text, int $maxLines = 20, string $truncateSuffix = '...'): array
{
$text = str_replace(["\r\n", "\r"], "\n", $text);
$lines = explode("\n", $text);
$lineCount = count($lines);
if ($lineCount <= $maxLines) {
return ['valid' => true, 'text' => $text, 'lineCount' => $lineCount];
}
// 截斷保留前 $maxLines 行
$truncated = implode("\n", array_slice($lines, 0, $maxLines)) . $truncateSuffix;
return ['valid' => false, 'text' => $truncated, 'lineCount' => $lineCount];
}
// 使用範例:留言送出處理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$content = $_POST['content'] ?? '';
$result = validateAndTruncateLines($content, 10);
if (!$result['valid']) {
echo "留言超過 10 行限制,已自動截斷:
";
echo nl2br(htmlspecialchars($result['text']));
} else {
echo "留言送出成功 (" . $result['lineCount'] . " 行)";
// 儲存 $result['text'] 到資料庫
}
}
<textarea id="comment" name="content" rows="6" maxlength="1000"></textarea>
<div id="lineInfo" class="hint">0 / 10 行</div>
<script>
const textarea = document.getElementById('comment');
const info = document.getElementById('lineInfo');
const MAX_LINES = 10;
function updateLineCount() {
// 統一換行符
const text = textarea.value.replace(/\r\n|\r/g, '\n');
const lines = text === '' ? 0 : text.split('\n').length;
info.textContent = `${lines} / ${MAX_LINES} 行`;
info.classList.toggle('over-limit', lines > MAX_LINES);
}
textarea.addEventListener('input', updateLineCount);
textarea.addEventListener('paste', () => setTimeout(updateLineCount, 0));
updateLineCount();
</script>
<style>
.hint { font-size: 0.875rem; color: #666; margin-top: 0.25rem; }
.hint.over-limit { color: #c00; font-weight: bold; }
</style>
| 方法 | 程式碼 | 速度 (1MB 文字) | 備註 |
|---|---|---|---|
substr_count | `substr_count($text, "\n")` | ~2 ms | C 實作,最快,推薦 |
preg_match_all | `preg_match_all('/\n/', $text)` | ~15 ms | 正規表示式開銷大 |
迴圈 strpos | 原始碼 `for` 迴圈 `strpos` | ~120 ms | PHP 迴圈慢,不推薦 |
使用 `substr_count` 搭配換行符標準化,即可高效、正確計算行數。結合後端驗證截斷與前端即時提示,提供完整的留言長度管控方案。