簡體   English   中英

在PHP 5.3中替換UTF-8字符

[英]Replacing UTF-8 characters in PHP 5.3

為什么這個測試用例不起作用?

<?php
// cards with cyrillic inidices and suits in UTF-8 encoding
$a = array('7♠', 'Д♠', 'К♠', '8♦', 'В♦', 'Д♦', '10♣', '10♥', 'В♥', 'Т♥');
foreach ($a as $card) {
        $suit = substr($card, -1);

        $card = preg_replace('/(\d+)♥/', '<span class="red">$1&hearts;</span>', $card);
        $card = preg_replace('/(\d+)♦/', '<span class="red">$1&diams;</span>', $card);
        $card = preg_replace('/(\d+)♠/', '<span class="black">$1&spades;</span>', $card);
        $card = preg_replace('/(\d+)♣/', '<span class="black">$1&clubs;</span>', $card);

        printf("suit: %s, html: %s\n", $suit, $card);
}
?>

輸出:

suit: ▒, html: <span class="black">7&spades;</span>
suit: ▒, html: Д♠
suit: ▒, html: К♠
suit: ▒, html: <span class="red">8&diams;</span>
suit: ▒, html: В♦
suit: ▒, html: Д♦
suit: ▒, html: <span class="black">10&clubs;</span>
suit: ▒, html: <span class="red">10&hearts;</span>
suit: ▒, html: В♥
suit: ▒, html: Т♥

即我在PHP腳本中遇到2個問題:

  1. 為什么不能正確提取最后一個UTF-8字符?
  2. 為什么只有第一套服裝被preg_replace取代?

使用PHP 5.3.3,PostgreSQL 8.4.12在CentOS 6.2上持有UTF-8 JSON(帶俄文和卡套裝)。

如果1.是PHP 5.3.3中的錯誤,那么有一個很好的解決方法嗎? (我不想升級庫存包)。

更新:

<?php
$a = array('7♠', 'Д♠', 'К♠', '8♦', 'В♦', 'Д♦', '10♣', '10♥', 'В♥', 'Т♥');
foreach ($a as $card) {
        $suit = mb_substr($card, -1, 1, 'UTF-8');

        $card = preg_replace('/(\d+)♥/u', '<span class="red">$1&hearts;</span>', $card);
        $card = preg_replace('/(\d+)♦/u', '<span class="red">$1&diams;</span>', $card);
        $card = preg_replace('/(\d+)♠/u', '<span class="black">$1&spades;</span>', $card);
        $card = preg_replace('/(\d+)♣/u', '<span class="black">$1&clubs;</span>', $card);

        printf("suit: %s, html: %s\n", $suit, $card);
}
?>

新輸出:

suit: ♠, html: <span class="black">7&spades;</span>
suit: ♠, html: Д♠
suit: ♠, html: К♠
suit: ♦, html: <span class="red">8&diams;</span>
suit: ♦, html: В♦
suit: ♦, html: Д♦
suit: ♣, html: <span class="black">10&clubs;</span>
suit: ♥, html: <span class="red">10&hearts;</span>
suit: ♥, html: В♥

substr是一個天真的PHP核心函數之一,它假設1個字節= 1個字符。 substr(..., -1)從字符串中提取最后一個字節 “♠”雖然長於一個字節。 您應該使用mb_substr($card, -1, 1, 'UTF-8')

您需要將u (PCRE_UTF8)修飾符添加到正則表達式,以使其正確處理UTF-8編碼的表達式和字符串:

preg_replace('/(\d+)♥/u', ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM