php 匹配替换中文

1、匹配中文

$str = "中文“;
preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$str,$match);

 

2、替换中文:

在所在的php文件里,要加上

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

这样才能支持多字节进行模式匹配。详细介绍:http://blog.chinaunix.net/uid-20279807-id-1711213.html

3、php提供了四个替换函数,分别是str_replace,preg_replace,mb_ereg_replace,ereg_replace(在php7.1已经摒弃掉)

   在替换中文时,发现用preg_replace替换中文最合适.

   str_replace 不支持正则表达式,不能完全匹配,导致局部字段被替换。例如: $str = "模块一 模块一断电",$str = str_replace("模块一","module1",$str);,导致"模块一断电"被替换成"module1断电"。

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )  支持$pattern,$replacement 以数组的方式进行查找替换,但数组过多时,进行搜索匹配,耗CPU严重。

 mb_ereg_replace 支持正则表达式,但不用分隔符//进行匹配,但使用mb_ereg_replace,发现有些中文匹配不了。具体原因暂不清楚。

 

posted @ 2017-03-08 18:22  cogitoergosum  阅读(4657)  评论(0编辑  收藏  举报