萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檢測字串換行數函式:留言板內容長度限制實用工具

需求:限制使用者留言的最大換行數,防止版面撐破或濫用

留言板、評論區常需限制「行數」而非單純字數。PHP 內建無直接函式,需自行實作。

基礎版:計算 `\n` 出現次數

<?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'] 到資料庫 } }

前端即時提示:JavaScript 同步驗證

<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 msC 實作,最快,推薦
preg_match_all`preg_match_all('/\n/', $text)`~15 ms正規表示式開銷大
迴圈 strpos原始碼 `for` 迴圈 `strpos`~120 msPHP 迴圈慢,不推薦

結語

使用 `substr_count` 搭配換行符標準化,即可高效、正確計算行數。結合後端驗證截斷與前端即時提示,提供完整的留言長度管控方案。

copyright © 萬盛學電腦網 all rights reserved