2
votes

Actually my expected result was- zero ০ one ১ two ২ three ৩ four ৪ five ৫ six ৬ seven ৭ eight ৮ nine ৯

But I got- zero &#ý৯;ý৯;3৭;৬;ý৯;ý৯;3৭;ý৯;3৮;; one &#ý৯;ý৯;3৭;৬;ý৯;ý৯;3৭;ý৯;;
two ý৯;ý৯;3৭;৬;
three ý৯;3৭;
four ý৯;3৮;
five ý৯;
six ৬
seven ৭
eight ৮
nine ৯ pleas help me. The code:

$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;
2
why not serve your page with a content-type encoding of UTF-8 and use the actual characters instead of the entities? - Gordon
Sorry content type utf-8 is not the solution. - user2056034
I've added <meta http-equiv="content-type" content="text/html; charset=utf-8;"> in <head> but the same result returned. - user2056034
meta tags are only used then server does not serve appropriate headers. Either set the content via php.net/headers or check your webserver configuration. - Gordon

2 Answers

1
votes

str_replace is not encoding-safe. you have an implementation of a multibyte str_replace ( mb_str_replace ) here :

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;
}

Edit: Oups, your characters are HTML encoded, not a PHP encoding problem.

1
votes

The function you want to use for this purpose is strtr().

$x = array("&#2534;", "&#2535;", "&#2536;", "&#2537;", "&#2538;", "&#2539;", "&#2540;", "&#2541;", "&#2542;", "&#2543;");
$converted = nl2br(strtr($on, $x));
echo $converted;

which produces the following:

O ০
one ১
two ২
three ৩
four ৪
five ৫
six ৬
seven ৭
eight ৮
nine ৯

str_replace() doesn't work here because the latter entries in the array is replacing characters in the replacement done by earlier entries.

P.S. The array really ought to be an associative array (i.e. "0" => "০"). I was too lazy to make the change and just use the fact that the integer keys happen to be right.