我需要为这个函数编写一个测试用例,但我似乎无法正确使用它。如果这意味着什么,我正在测试我的本地机器。
function cleanEncoding($a)
// Replace specified foreign character with equivalent english character
{ $filter = ['"' => '"',
'"' => '"',
'&' => '&',
'&' => '&',
'<' => '<',
'&#lt;' => '<',
'>' => '>',
'&#gt;' => '>',
' ' => ' ',
'à' => 'a',
'á' => 'a',
'â' => 'a',
'ã' => 'a',
'ä' => 'a',
'å' => 'a',
'æ' => 'a',
'ç' => 'c',
'è' => 'e',
'é' => 'e',
'ê' => 'e',
'ë' => 'e',
'ì' => 'i',
'í' => 'i',
'î' => 'i',
'ï' => 'i',
'ñ' => 'n',
'ð' => 'o',
'ò' => 'o',
'ó' => 'o',
'ô' => 'o',
'õ' => 'o',
'ö' => 'o',
'ø' => 'o',
'ù' => 'u',
'ú' => 'u',
'û' => 'u',
'ü' => 'u',
'ý' => 'y',
'ÿ' => 'y',
'œ' => 'oe',
'š' => 's',
'À' => 'A',
'Á' => 'A',
'Â' => 'A',
'Ã' => 'A',
'Ä' => 'A',
'Å' => 'A',
'Æ' => 'A',
'Ç' => 'C',
'È' => 'E',
'É' => 'E',
'Ê' => 'E',
'Ë' => 'E',
'Ì' => 'I',
'Í' => 'I',
'Î' => 'I',
'Ï' => 'I',
'Ñ' => 'N',
'Ò' => 'O',
'Ó' => 'O',
'Ô' => 'O',
'Õ' => 'O',
'Ö' => 'O',
'Ø' => 'O',
'Ù' => 'U',
'Ú' => 'U',
'Û' => 'U',
'Ü' => 'U',
'Ý' => 'Y',
'Ÿ' => 'Y',
'Œ' => 'OE',
'Š' => 'S',];
// replace foreign character with equivalent english character
foreach ($filter as $b => $c) {
$d = str_replace($b, $c, $a);
}
// deletes foreign character that was not found
$d = preg_replace(("/&#[0-9]*;/","",$a);
return ($a);
}
这是我的测试代码。它打印出来但仍然是外国字符。我需要用等同的英文字符打印。
$a = 'Hêllø Wôrld!$';
$e = cleanEncoding($a);
echo $e;
答案 0 :(得分:1)
正如其他人所指出的那样,您的str_replace
,preg_replace
和return
似乎存在问题。
迭代过滤器:
foreach ($filter as $key => $value) {
$a = str_replace($key, $value, $a);
}
然后用空白字符串替换任何未找到的内容:
$a = preg_replace("/&#[0-9]*;/","", $a);
然后返回该字符串:
return $a;
答案 1 :(得分:0)
试试这个,你的代码有一些语法错误
function cleanEncoding($a){
// Replace specified foreign character with equivalent english character
$filter = Array('"' => '"',
'"' => '"',
'&' => '&',
'&' => '&',
'<' => '<',
'&#lt;' => '<',
'>' => '>',
'&#gt;' => '>',
' ' => ' ',
'à' => 'a',
'á' => 'a',
'â' => 'a',
'ã' => 'a',
'ä' => 'a',
'å' => 'a',
'æ' => 'a',
'ç' => 'c',
'è' => 'e',
'é' => 'e',
'ê' => 'e',
'ë' => 'e',
'ì' => 'i',
'í' => 'i',
'î' => 'i',
'ï' => 'i',
'ñ' => 'n',
'ð' => 'o',
'ò' => 'o',
'ó' => 'o',
'ô' => 'o',
'õ' => 'o',
'ö' => 'o',
'ø' => 'o',
'ù' => 'u',
'ú' => 'u',
'û' => 'u',
'ü' => 'u',
'ý' => 'y',
'ÿ' => 'y',
'œ' => 'oe',
'š' => 's',
'À' => 'A',
'Á' => 'A',
'Â' => 'A',
'Ã' => 'A',
'Ä' => 'A',
'Å' => 'A',
'Æ' => 'A',
'Ç' => 'C',
'È' => 'E',
'É' => 'E',
'Ê' => 'E',
'Ë' => 'E',
'Ì' => 'I',
'Í' => 'I',
'Î' => 'I',
'Ï' => 'I',
'Ñ' => 'N',
'Ò' => 'O',
'Ó' => 'O',
'Ô' => 'O',
'Õ' => 'O',
'Ö' => 'O',
'Ø' => 'O',
'Ù' => 'U',
'Ú' => 'U',
'Û' => 'U',
'Ü' => 'U',
'Ý' => 'Y',
'Ÿ' => 'Y',
'Œ' => 'OE',
'Š' => 'S');
// replace foreign character with equivalent english character
$d=$a;
foreach ($filter as $b => $c) {
$d = str_replace($b, $c, $d);
}
// deletes foreign character that was not found
$d = preg_replace("/&#[0-9]*;/","",$d);
return ($d);
}
$a = 'Hêllø Wôrld!$';
$e = cleanEncoding($a);
echo $e;