关于字符串:使用php将数字转换为utf-8 unicode

Number to utf-8 unicode converting using php

实际上,我的预期结果是-
零?
一个?
两个?
三个?
四?
五?
六个?
七 ?
八个?
九点?

但是我得到了
零y?; 3?;?; y?; y?; 3?; y?; 3?;;
一个y?; 3?;?; y?; y?; 3?; y?;;
两个y?; y?; 3?;?;
三个y?; 3 ?;
4 y?; 3 ?;
五岁?;
六个?
七个?
八个?
九点?
请帮我。
代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$n=array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

 $x=array("","","","","","","","","","");

$on='O 0
 one 1
 two 2
 three 3
 four 4
 five 5
 six 6
 seven 7
 eight 8
 nine 9'
;

 $converted = nl2br(str_replace($n, $x, $on));


 echo $converted;


您要用于此目的的函数是strtr()。

1
2
3
$x = array("","","","","","","","","","");
$converted = nl2br(strtr($on, $x));
echo $converted;

产生以下内容:

O
one
two
three

four
five
six
seven
eight
nine

str_replace()在这里不起作用,因为数组中的后一个条目正在替换由较早的条目完成的替换中的字符。

附言 该数组确实应该是一个关联数组(即" 0" =>"")。 我懒得进行更改,只是使用整数键恰好是正确的事实。


str_replace不是编码安全的。 您在这里有一个多字节str_replace(mb_str_replace)的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
function mb_str_replace($needle, $replacement, $haystack)
{
    $needle_len = mb_strlen($needle);
    $replacement_len = mb_strlen($replacement);
    $pos = mb_strpos($haystack, $needle);
    while ($pos !== false)
    {
        $haystack = mb_substr($haystack, 0, $pos) . $replacement
                . mb_substr($haystack, $pos + $needle_len);
        $pos = mb_strpos($haystack, $needle, $pos + $replacement_len);
    }
    return $haystack;
}

编辑:糟糕,您的字符是HTML编码的,不是PHP编码的问题。