尋找一個reg前爲null(空)的字符串,如果任何包含壞詞..的Preg更換 - REG前需要
$string1 = "Ihatestackoverflow";
$string2 = "I HaTe sackoverflow";
$string3 = "1HaTestackoverflow";
$badword = "hate";
# result
# string1 = "";
# string2 = "";
# string3 = "";
尋找一個reg前爲null(空)的字符串,如果任何包含壞詞..的Preg更換 - REG前需要
$string1 = "Ihatestackoverflow";
$string2 = "I HaTe sackoverflow";
$string3 = "1HaTestackoverflow";
$badword = "hate";
# result
# string1 = "";
# string2 = "";
# string3 = "";
$regex = '#^.*?(hate).*$#ims';
$str = preg_replace($regex, '', $str);
要添加更多的「髒話」,只需添加他們在()中:
$regex = '#^.*?(hate|anotherbadword|yetanother|etc).*$#ims';
前導^和尾部$匹配完整字符串。 i選項用於不區分大小寫的匹配。 m啓用多行模式(以便^和$匹配整個字符串,而不是單行)。這個s啓用DOTALL(所以。也匹配換行符)。
你可以
,你可以存儲所有你不想要的話在一個數組並重復他們的選擇。 '$ bad = array(...); for($ i = 0; $ i
@Matt S:如果你打算使用循環,我會使用'stripos() ...像foreach($ bad as $ word){if(stripos($ string,$ word)!== false){$ string =''; break;}}'。休息是因此,一旦你殺了字符串,你不會繼續循環。或者你可以從循環中構建正則表達式:'$ regex ='#^。*?('; foreach($ bad as $ word){$ regex。= preg_quote($ word,'#')。'|'; } $ regex = rtrim($ regex,'|')。')。* $#ims';'... – ircmaxell 2010-06-04 20:07:13
正確,我個人不喜歡在我的語句中使用break,這就是爲什麼我使用'for() '而不是'foreach()'。你當然是正確的'stripos'是一個比正則表達式更好的選擇。 – 2010-06-05 15:31:31
您需要閱讀http://en.wikipedia.org/wiki/Scunthorpe_problem – 2010-06-04 20:03:24