有没有人写过函数strtr()的多字节变体?我需要这个。
编辑1(所需用法示例):
Example: $from = 'ľľščťžýáíŕďňäô'; // these chars are in UTF-8 $to = 'llsctzyaiŕdnao'; // input - in UTF-8 $str = 'Kŕdeľ ďatľov učí koňa žrať kôru.'; $str = mb_strtr( $str, $from, $to ); // output - str without diacritic // $str = 'Krdel datlov uci kona zrat koru.';
答案 0 :(得分:24)
我相信 strtr
is multi-byte safe,无论哪种方式,因为str_replace
是多字节安全,你可以把它包起来:
function mb_strtr($str, $from, $to)
{
return str_replace(mb_str_split($from), mb_str_split($to), $str);
}
由于没有mb_str_split
功能,您还需要编写自己的功能(使用mb_substr
和mb_strlen
),或者您可以使用PHP UTF-8实施(稍微更改) ):
function mb_str_split($str) {
return preg_split('~~u', $str, null, PREG_SPLIT_NO_EMPTY);;
}
但是,如果您正在寻找从字符串中删除所有(拉丁?)重音的功能,您可能会发现以下功能有用:
function Unaccent($string)
{
return preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'));
}
echo Unaccent('ľľščťžýáíŕďňä'); // llsctzyairdna
echo Unaccent('Iñtërnâtiônàlizætiøn'); // Internationalizaetion
答案 1 :(得分:2)
function mb_strtr($str,$map,$enc){
$out="";
$strLn=mb_strlen($str,$enc);
$maxKeyLn=1;
foreach($map as $key=>$val){
$keyLn=mb_strlen($key,$enc);
if($keyLn>$maxKeyLn){
$maxKeyLn=$keyLn;
}
}
for($offset=0; $offset<$strLn; ){
for($ln=$maxKeyLn; $ln>=1; $ln--){
$cmp=mb_substr($str,$offset,$ln,$enc);
if(isset($map[$cmp])){
$out.=$map[$cmp];
$offset+=$ln;
continue 2;
}
}
$out.=mb_substr($str,$offset,1,$enc);
$offset++;
}
return $out;
}
答案 2 :(得分:1)
可能使用str_replace是一个很好的解决方案。另一种选择:
<?php
header('Content-Type: text/plain;charset=utf-8');
function my_strtr($inputStr, $from, $to, $encoding = 'UTF-8') {
$inputStrLength = mb_strlen($inputStr, $encoding);
$translated = '';
for($i = 0; $i < $inputStrLength; $i++) {
$currentChar = mb_substr($inputStr, $i, 1, $encoding);
$translatedCharPos = mb_strpos($from, $currentChar, 0, $encoding);
if($translatedCharPos === false) {
$translated .= $currentChar;
}
else {
$translated .= mb_substr($to, $translatedCharPos, 1, $encoding);
}
}
return $translated;
}
$from = 'ľľščťžýáíŕďňä'; // these chars are in UTF-8
$to = 'llsctzyairdna';
// input - in UTF-8
$str = 'Kŕdeľ ďatľov učí koňa žrať kôru.';
print 'Original: ';
print chr(10);
print $str;
print chr(10);
print chr(10);
print 'Tranlated: ';
print chr(10);
print my_strtr( $str, $from, $to);
使用PHP 5.2在我的机器上打印:
Original:
Kŕdeľ ďatľov učí koňa žrať kôru.
Tranlated:
Krdel datlov uci kona zrat kôru.