如何在PHP中用latin1字符串替换特殊字符?

时间:2018-01-05 17:39:12

标签: php mysql string utf-8 str-replace

当我尝试将“Ñ”替换为“N”或“Ç”替换为“C”或“Ü”替换为“U”时,我遇到了问题,例如PHP from strings latin1 codified < /强>

我从mySQL中检索UTF-8编码此字符串“IBAÑEZRIBERA,ALBA”,我想将“Ñ”替换为“N”并获得“IBANEZ RIBERA,ALBA”,但我有几个问题。< / p>

如果我使用str_replace它不起作用,如果我使用iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', "IBAÑEZ RIBERA, ALBA")我得到的是“IBAEZ RIBERA,ALBA”,其中这个字符“Ñ”被删除而不是被“N”替换我喜欢什么它

那么,我该怎么做呢?

编辑I:

我观察过,如果我在mySQL Workbench中使用mySQL函数替换chars,请查询:

select id, id_player, name, replace(replace(replace(replace(name, " ", "-"), ",", " "), " ", ""), 'Ñ', 'N') as urlName 
from tbl003_player p, (select id_player from tbl006_player_club where id = 188) pc where 
p.id = pc.id_player;

我在“urlName”字段中得到了我想要的结果!!!

enter image description here

但是,当我尝试从我得到的查询中检索PHP中的这些数据时:

“IBAÑEZ-RIBERA-ALBA”

发生了什么事?

1 个答案:

答案 0 :(得分:1)

试试这个:

<?php

$string = 'IBAÑEZ RIBERA, ALBA, á â à å ä ð é ê è ë í î ì ï ó ô ò ø õ ö ú û ù ü æ ç ß abc ABC 123';

$value = iconv('UTF-8','ASCII//TRANSLIT',$string);

echo $value;
?>

将产生输出:

IBANEZ RIBERA, ALBA, a a a a a d e e e e i i i i o o o o o o u u u u ae c ss abc ABC 123

更新:

由于我在这个答案或评论中没有提到任何问题,请使用:

<?php

$string = 'IBAÑEZ RIBERA, ALBA'; 

function changeChar($string){

$chars = array(
    'À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A',
    'Æ'=>'A','Ç'=>'C','È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E',
    'Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I','Ð'=>'Dj','Ñ'=>'N',
    'Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O','Ø'=>'O',
    'Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U','Ý'=>'Y','Þ'=>'B',
    'ß'=>'Ss','à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a',
    'å'=>'a','æ'=>'a','ç'=>'c','è'=>'e','é'=>'e','ê'=>'e',
    'ë'=>'e','ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ð'=>'o',
    'ñ'=>'n','ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o',
    'ø'=>'o','ù'=>'u','ú'=>'u','û'=>'u','ü'=>'u','ý'=>'y',
    'þ'=>'b','ÿ'=>'y','Ă'=>'A','ă'=>'a','Ń'=>'N','ń'=>'n',
    'Š'=>'S','š'=>'s','Ž'=>'Z','ž'=>'z','ƒ'=>'f','Ș'=>'S',
    'ș'=>'s','Ț'=>'T','ț'=>'t',
);
    return strtr($string, $chars);
    //or return str_replace(array_keys($chars), array_values($chars), $string);
}

echo changeChar($string);

它并不漂亮,但在大多数情况下都可以使用。