php 正则匹配中文 (2011-09-26 10:10:46)
标签: 杂谈 分类: 专业篇
转载:http://hi.baidu.com/?_d/blog/item/063b77d5432f8f1aa18bb7fd.html
在javascript中,要判断字符串是中文是很简单的。比如:
var str = "php编程";
if (/^[\u4e00-\u9fa5]+$/.test(str)) {
alert("该字符串全部是中文");
} else {
alert("该字符串不全部是中文");
}
想当然的,在php中来判断字符串是否为中文,就会沿袭这个思路:
$str = "php编程";
if (preg_match("/^[\u4e00-\u9fa5]+$/",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
?>
不过,很快就会发现,php并不支持这样的表达,报错:
Warning: preg_match() [function.preg-match]: Compilation failed: PCRE does not support \L, \l, \N, \U, or \u at offset 3 in test.php on line 3
刚开始从google上查了很多次,想从php正则表达式对于十六进制数据的
表达方式上进行突破,发现在php中,是用\x表示十六进制数据的。于是,
变换成如下的代码:
$str = "php编程";
if (preg_match("/^[\x4e00-\x9fa5]+$/",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
貌似不报错了,判断的结果也正确,不过把$str换成“编程”两字,结果却
还是显示“该字符串不全部是中文”,看来这样的判断还是不够准确。
后来跑回百度搜“php 匹配汉字 utf 8”,发现文章的匹配程度竟然要比google的高多了,
看来百度的“百度更懂中文”还在一定程度上是正确的。在第二篇文章《★★★ 求UTF8
下匹配汉字的正则, 在线等.........》中看到了如下的一些内容:
楼主zhiin(┈ Jcan ┈)2006-11-15 15:59:30 在 Web 开发 / PHP 提问
求UTF8下匹配汉字的正则, 不包括全角字符及特殊符号!
网上只能找到匹配全角字符的正则: ^[\x80-\xff]*^/
[\u4e00-\u9fa5]可以匹配中文,但是PHP又不支持
郁闷中.......
1 楼PleaseDoTellMeWhy(Allah bless you!)回复于 2006-11-15 16:04:55 得分 11
chr(0xa1) . '-' . chr(0xff)可以匹配所有中文,但是不知道在UTF-8下如何!Top
2 楼zhiin(┈ Jcan ┈)回复于 2006-11-15 16:11:34 得分 0
即使在gb2312下, chr(0xa1) . '-' . chr(0xff) 也不对
它把全角符号也匹配进来了Top
3 楼xuzuning(唠叨)回复于 2006-11-15 16:19:56 得分 90
模式修正符: u
按照这几位提供的线索逐个试了一下,发现还真的如他们所说,可能还跟编码有关系,
因此需要了解一下模式修正符的相关知识??于是继续搜索百度。
在一篇《模式修正符》的文章中了解到:
u (PCRE_UTF8)
此修正符启用了一个 PCRE 中与 Perl 不兼容的额外功能。模式字符串被当成 UTF-8。
本修正符在 Unix 下自 PHP 4.1.0 起可用,在 win32 下自 PHP 4.2.3 起可用。
例子:
preg_match('/[\x{2460}-\x{2468}]/u', $str); 匹配 内码汉字
按照他提供的方式进行测试,代码如下:
$str = "php编程";
if (preg_match("/^[\x{2460}-\x{2468}]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
发现这次依然对是否为中文判断失常。不过,既然\x表示的十六进制数据,
为什么和js里边提供的范围\x4e00-\x9fa5不一样呢?于是我就换成了下边的代码:
$str = "php编程";
if (preg_match("/^[\x4e00-\x9fa5]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
本来以为铁定成功了的事情,没想到,warning又一次产生了:
Warning: preg_match() [function.preg-match]: Compilation failed: invalid UTF-8 string at offset 6 in test.php on line 3
看来又有错误的表达方式了,于是对照了一下那篇文章的表达方式,
给“4e00”和“9fa5”两边分别用"{"和“}”包起来,跑了一遍,发现真的准确了:
$str = "php编程";
if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
知道了php中utf-8编码下用正则表达式匹配汉字的最终正确表达式??/^[\x{4e00}-\x{9fa5}]+$/u,
于是我又用这个表达式去百度搜索,发现竟然还真有别人得出过这样正确的结论,只不过通过
常规的方式很难找到而已,而且仅仅搜到有一篇??《用正则删除汉字》,看来互联网上对于
信息的正确性的筛选还是亟待加强的。
ps:对google不死心,也搜索了一下,又发现了一篇文章《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"您输入的[".$str."]含有违法字符";
}
else
{
echo "您输入的[".$str."]完全合法,通过!";
}
}
?>
(转)

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor
