PHP 中将全角字符转换成半角的方法

发布时间:2008年12月24日      浏览次数:686 次
摘要: 在许多收集用户信息的表单里,期望用户输入的是半角字符,但是无论你如何强调,如何提醒,还是会有粗心的用户提交全角数据,其实,在一些新手眼中,全角和半角根本就没有区别,甚至他们会觉得:我提交的明明是正确的信息,为什么会提示错误呢?
实际上,全角和半角有一一对应关系,而大多数用户并非故意输入错误的信息,所以,我们可以通过程序来避免这种情况的发生,最多,可以在转换后给用户一个确认的机会,这样,或许能够给用户一个更好的体验。 全半角英文数字的替换函数
//全角替换到半角
function SBC_DBC($Str) {
$Queue = Array(
'0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
'5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
'y' => 'y', 'z' => 'z', '-' => '-', ' ' => ' '
);
return preg_replace("/([\xA3][\xB0-\xB9\xC1-\xDA\xE1-\xFA])/e", "\$Queue[\\1]", $Str);
}
//半角替换到全角
function DBC_SBC($Str) {
$Queue = Array(
'0' => '0','1' => '1','2' => '2','3' => '3','4' => '4',
'5' => '5','6' => '6','7' => '7','8' => '8','9' => '9',
'A' => 'A','B' => 'B','C' => 'C','D' => 'D','E' => 'E',
'F' => 'F','G' => 'G','H' => 'H','I' => 'I','J' => 'J',
'K' => 'K','L' => 'L','M' => 'M','N' => 'N','O' => 'O',
'P' => 'P','Q' => 'Q','R' => 'R','S' => 'S','T' => 'T',
'U' => 'U','V' => 'V','W' => 'W','X' => 'X','Y' => 'Y',
'Z' => 'Z','a' => 'a','b' => 'b','c' => 'c','d' => 'd',
'e' => 'e','f' => 'f','g' => 'g','h' => 'h','i' => 'i',
'j' => 'j','k' => 'k','l' => 'l','m' => 'm','n' => 'n',
'o' => 'o','p' => 'p','q' => 'q','r' => 'r','s' => 's',
't' => 't','u' => 'u','v' => 'v','w' => 'w','x' => 'x',
'y' => 'y','z' => 'z'
);
return preg_replace("/([0-9a-zA-Z])/e", "\$Queue[\\1]", $Str);
}
///判断字符传中是否包含全角英文或者数字
$p = "/([\xA3][\xB0-\xB9\xC1-\xDA\xE1-\xFA])/e";
if(preg_match($p,$str)){
echo "yes";
}else{
echo "no";
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!