萬盛學電腦網

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

PHP 將多行文本轉為 JavaScript 字串:模板字面量時代的最佳實踐

問題背景

JavaScript 歷不支援多行字串(ES6 前),開發者常需將 HTML 模板、SQL、長文本轉為 JS 可用格式:

// 手寫極其痛苦
var html = '
row 1
' + '
row 2
' + '
row 3
';

現代解法:ES6 模板字面量(推薦)

<script type="module">
// 直接支援多行、插值、標籤模板
const template = `
  

${title}

${content}

`; </script>

**現代專案請直接使用模板字面量**,無需後端轉換。

歷史專案相容:PHP 轉換工具

若必須支援舊瀏覽器或舊代碼庫,PHP 可提供轉換工具:

<?php
/**
 * 多行文本轉 JS 字串連接格式
 * @param string $text  多行文本
 * @param string $quote 引號類型:'single' | 'double' | 'backtick'
 * @param bool   $es6   是否輸出 ES6 模板字面量(預設 false 為相容模式)
 * @return string
 */
function textToJsString(string $text, string $quote = 'single', bool $es6 = false): string
{
    $text = normalizeLineEndings($text);
    $lines = explode("\n", $text);
    
    if ($es6) {
        // ES6 模板字面量:需轉義反引號、$、{
        $escaped = str_replace(['\\', '`', '$', '{'], ['\\\\', '\\`', '\\$', '\\{'], $text);
        return "`{$escaped}`";
    }

    $quoteChar = $quote === 'double' ? '"' : "'";
    $escapeMap = [
        '\\' => '\\\\',
        $quoteChar => '\\' . $quoteChar,
        "\n" => '\\n',
        "\r" => '\\r',
        "\t" => '\\t',
    ];
    
    $parts = [];
    foreach ($lines as $i => $line) {
        $escaped = strtr($line, $escapeMap);
        if ($i === 0) {
            $parts[] = "{$quoteChar}{$escaped}{$quoteChar}";
        } else {
            $parts[] = " + {$quoteChar}{$escaped}{$quoteChar}";
        }
    }
    return implode("\n", $parts);
}

function normalizeLineEndings(string $text): string
{
    return str_replace(["\r\n", "\r"], "\n", $text);
}

// === Web 介面工具頁 ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = $_POST['text'] ?? '';
    $quote = $_POST['quote'] ?? 'single';
    $es6 = isset($_POST['es6']);
    $output = textToJsString($input, $quote, $es6);
}
?>



    
    Text to JS String Converter
    


    

多行文本 → JS 字串轉換器





結果

進階:直接輸出 JS 變數宣告(含變數名)

<?php
function textToJsVar(string $varName, string $text, bool $es6 = false, bool $const = true): string
{
    $jsString = textToJsString($text, 'single', $es6);
    $keyword = $const ? 'const' : 'let';
    return "{$keyword} {$varName} = {$jsString};";
}

// 範例
$html = <<
  
標題
內容區域
底部
HTML; echo textToJsVar('modalTemplate', $html, true); // 輸出:const modalTemplate = ``; ?>

建構工具整合:Vite/Webpack/Laravel Mix

現代建構工具已內建處理,無需手動轉換:

Vite / Vue / React

<!-- 直接 import .html 或 .txt -->
<script setup>
import template from './template.html?raw'
// template 即為字串
</script>

Laravel Blade + Vite

// resources/js/components/Modal.vue


舊專案:Laravel Mix + raw-loader

// webpack.mix.js
mix.webpackConfig({
    module: {
        rules: [
            { test: /\.html$/, use: 'raw-loader' },
        ]
    }
});

安全性提醒

  • **永遠不要**將未經過 XSS 過濾的使用者輸入直接輸出到 JS 字串
  • 轉換工具僅供開發期使用,**不可暴露為公開 API**
  • 生產環境模板應經過建構工具處理,而非執行期 PHP 轉換

總結建議

專案類型推薦方案
現代專案ES6 模板字面量 + 建構工具 import raw
需支援 IE11Babel 轉譯模板字面量,或 PHP 工具產生連接字串
純 PHP 專案輸出 JSPHP 函數產生連接字串,配合 json_encode 確保安全
動態模板需求後端渲染 Blade/Twig,前端僅負責資料綁定

隨著 ES6 普及率超過 99%,「PHP 轉 JS 字串」已成為歷史需求。新專案請直接使用模板字面量與建構工具,舊專案可用本文工具過渡升級。

copyright © 萬盛學電腦網 all rights reserved