日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php替换中文,PHP中文替换

發布時間:2023/12/9 php 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php替换中文,PHP中文替换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

//定義編碼

header(?'Content-Type:text/html;charset=utf-8 ');

$words=array('我','你','他');

$content="測一測我是不是違禁詞";

$banned=generateRegularExpression($words);

//檢查違禁詞

$res_banned=check_words($banned,$content);

write_html($content,$res_banned);

/**

* @describe 數組生成正則表達式

* @param array $words

* @return string

*/

function?generateRegularExpression($words)

{

$regular?= implode('|',?array_map('preg_quote',?$words));

return?"/$regular/i";

}

/**

* @describe 字符串 生成正則表達式

* @param array $words

* @return string

*/

function?generateRegularExpressionString($string){

$str_arr[0]=$string;

$str_new_arr=??array_map('preg_quote',?$str_arr);

return?$str_new_arr[0];

}

/**

* 檢查敏感詞

* @param $banned

* @param $string

* @return bool|string

*/

function?check_words($banned,$string)

{????$match_banned=array();

//循環查出所有敏感詞

$new_banned=strtolower($banned);

$i=0;

do{

$matches=null;

if?(!empty($new_banned) && preg_match($new_banned,?$string,?$matches)) {

$isempyt=empty($matches[0]);

if(!$isempyt){

$match_banned?=?array_merge($match_banned,?$matches);

$matches_str=strtolower(generateRegularExpressionString($matches[0]));

$new_banned=str_replace("|".$matches_str."|","|",$new_banned);

$new_banned=str_replace("/".$matches_str."|","/",$new_banned);

$new_banned=str_replace("|".$matches_str."/","/",$new_banned);

}

}

$i++;

if($i>20){

$isempyt=true;

break;

}

}while(count($matches)>0 && !$isempyt);

//查出敏感詞

if($match_banned){

return?$match_banned;

}

//沒有查出敏感詞

return?array();

}

/**

* 打印到頁面上

* @param $filepath

* @param $res_mingan

* @param $res_banned

*/

function?write_html($content,$res_banned){

print_r($content);

if($res_banned){

print_r("? 違禁詞(".count($res_banned)."):".implode('|',$res_banned));

}

echo?"
";

}

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,發現有些中文匹配不了。具體原因暫不清楚。

總結

以上是生活随笔為你收集整理的php替换中文,PHP中文替换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。