php替換中文字符的方法:首先利用strpos()函數(shù)找到中文字符在另一字符串中出現(xiàn)的位置,如果找不到中文字符則返回false;然后利用substr_replace()函數(shù)把中文字符替換掉即可。
strpos()返回字符串在另一字符串中第一次出現(xiàn)的位置,如果沒有找到字符串則返回 FALSE。
(推薦教程:php圖文教程)
語法:
strpos(string,find,start)
參數(shù):
-
string 必需。規(guī)定被搜索的字符串。
-
find 必需。規(guī)定要查找的字符。
-
start 可選。規(guī)定開始搜索的位置。
substr_replace() 函數(shù)把字符串的一部分替換為另一個字符串,并返回被替換的字符串。如果 string 是數(shù)組,則返回數(shù)組。
(視頻教程推薦:php視頻教程)
語法:
substr_replace(string,replacement,start,length)
實現(xiàn)代碼:
$words = ["我", "你", "他", "她"];//過濾庫 $sentence = "我和你一起去他家找她";//待過濾的句子 foreach($words as $word)//遍歷過濾庫的詞 { $len = strlen($word);//獲取過濾詞的長度 $pos = strpos($sentence,$word);//尋找過濾詞的位置 $sentence = substr_replace($sentence,'', $pos, $len); } echo $sentence;