首頁  >  文章  >  後端開發  >  如何在PHP轉換各種智慧引號?

如何在PHP轉換各種智慧引號?

Susan Sarandon
Susan Sarandon原創
2024-10-22 06:53:30391瀏覽

How Can I Convert Various Smart Quotes in PHP?

在PHP 中轉換各種智慧引號

智慧引號是標準引號的常見變體,在排版中用於增強可讀性和美觀性文字的吸引力。為了確保在處理文字時將這些智慧引號正確轉換為常規引號,必須考慮在不同上下文中使用的各種智慧引號字元。

改進的智慧引號轉換功能:

以下增強功能透過合併各種智慧引號字元的全面映射來解決您提供的原始功能的缺點。它利用字元映射($chr_map) 和預先計算的陣列($chr 和$rpl)來實現最佳效率:

<code class="php">$chr_map = array(
    "\xC2\x82" => "'", // U+0082⇒U+201A single low-9 quotation mark
    "\xC2\x84" => '"', // U+0084⇒U+201E double low-9 quotation mark
    "\xC2\x8B" => "'", // U+008B⇒U+2039 single left-pointing angle quotation mark
    "\xC2\x91" => "'", // U+0091⇒U+2018 left single quotation mark
    "\xC2\x92" => "'", // U+0092⇒U+2019 right single quotation mark
    "\xC2\x93" => '"', // U+0093⇒U+201C left double quotation mark
    "\xC2\x94" => '"', // U+0094⇒U+201D right double quotation mark
    "\xC2\x9B" => "'", // U+009B⇒U+203A single right-pointing angle quotation mark

    "\xC2\xAB" => '"', // U+00AB left-pointing double angle quotation mark
    "\xC2\xBB" => '"', // U+00BB right-pointing double angle quotation mark
    "\xE2\x80\x98" => "'", // U+2018 left single quotation mark
    "\xE2\x80\x99" => "'", // U+2019 right single quotation mark
    "\xE2\x80\x9A" => "'", // U+201A single low-9 quotation mark
    "\xE2\x80\x9B" => "'", // U+201B single high-reversed-9 quotation mark
    "\xE2\x80\x9C" => '"', // U+201C left double quotation mark
    "\xE2\x80\x9D" => '"', // U+201D right double quotation mark
    "\xE2\x80\x9E" => '"', // U+201E double low-9 quotation mark
    "\xE2\x80\x9F" => '"', // U+201F double high-reversed-9 quotation mark
    "\xE2\x80\xB9" => "'", // U+2039 single left-pointing angle quotation mark
    "\xE2\x80\xBA" => "'", // U+203A single right-pointing angle quotation mark
);

$chr = array_keys($chr_map); // but: for efficiency you should
$rpl = array_values($chr_map); // pre-calculate these two arrays
$str = str_replace($chr, $rpl, html_entity_decode($str, ENT_QUOTES, "UTF-8"));</code>

此改進的函數採用符合Unicode 的方法,涵蓋了全面的範圍智慧引號字元。透過利用預先計算的數組,它保持高效率,同時確保智慧報價準確轉換為標準報價。

其他注意事項:

  • 編碼偵測:如果輸入編碼不確定,請在應用上述函數之前使用 utf8_encode() 確保 UTF-8 編碼。
  • 標準化 Windows 代碼頁 1252:對於可能源自 Windows 代碼頁 1252 的文本,請考慮使用標準化映射將特定代碼點轉換為其 Unicode 等效項。
  • Unicode 字元屬性:使用字元屬性可以進一步增強智慧引號處理,但它們在正規表示式中的可用性有限。

以上是如何在PHP轉換各種智慧引號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn