网络营销电子商务研究中心  
How to buy the best prescription safety glasses in Canada? Let's study!
Go Back   网络营销电子商务研究中心 > 网站设计 > PHP
User Name
Password
 
FAQ Members List Calendar Cheap Glasses Mark Forums Read

 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
  #1   IP: 180.125.23.91
Old 2016-02-28, 05:12 PM
Apalachin Apalachin is offline
初级会员
 
Join Date: 2013-09-20
Posts: 1
Apalachin 现在声名狼藉
Default php判断字符是否为中文

编写php程序的时候,可能会遇到判断字符是否是中文的问题,这里给大家分享一下自己的经验,我测试了下,是好用的。


工具/原料


php


一台本地的php服务器,例如phpstudy



方法/步骤

首先,需要知道一下常见的编码范围

1. GBK (GB2312/GB18030)

\x00-\xff GBK双字节编码范围\x20-\x7f ASCII\xa1-\xff 中文\x80-\xff 中文 2. UTF-8 (Unicode)

\u4e00-\u9fa5 (中文)\x3130-\x318F (韩文\xAC00-\xD7A3 (韩文)\u0800-\u4e00 (日文)正则表达式的例子reg_replace(”/([\x80-\xff])/”,”",$str);preg_replace(”/([u4e00-u9fa5])/”,”",$str


在javascript中,要判断字符串是中文是很简单的。比如:var str = "php编程";if (/^[\u4e00-\u9fa5]+$/.test(str)) {alert("该字符串全部是中文");}else{alert("该字符串不全部是中文");}

php中,是用\x表示十六进制数据的。于是,变换成如下的代码:$str = "php编程";if (preg_match("/^[\x4e00-\x9fa5]+$/",$str)) {print("该字符串全部是中文");} else {print("该字符串不全部是中文");}不报错了,但是有些汉字测试的时候,结果却还是显示“该字符串不全部是中文”,看来这样的判断还是不够准确。


php中utf-8编码下用正则表达式匹配汉字的最终正确表达式——/^[\x{4e00}-\x{9fa5}]+$/u


复制以下代码保存成.php文件,测试完全通过:

<?php$action = trim($_GET['action']);if($action == "sub"){ $str = $_POST['dir']; //if(!preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/",$str)) //GB2312汉字字母数字下划线正则表达式 if(!preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",$str))//UTF-8汉字字母数字下划线正则表达式 { echo "<font color=red>您输入的[".$str."]含有违法字符</font>"; } else { echo "<font color=green>您输入的[".$str."]完全合法,通过!</font>"; }}?><form method="POST" action="?action=sub">输入字符(数字,字母,汉字,下划线): <input type="text" name="dir" value=""> <input type="submit" value="提交"></form>



注意事项


如果想判断一个字符串内是否有含有中文,请用下面的代码: if (preg_match("/[\x7f-\xff]/", $string)) { echo "有中文"; }else{ echo "没有中文"; }
Reply With Quote
 


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Prescription-glasses.com offers prescription glasses online at discount prices.
All times are GMT +8. The time now is 07:44 AM.


Powered by vBulletin Version 3.8.7
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.