Categories
PHP phpexperts

Replace bad words in a string

Recently I came accross a pretty interesting problem through my group, phpexperts where someone needed a solution to replace badwords, but not if that word is a part of another word. For example if you consider the word “some” as bad, then you can replace all “some”, “.some”,”some,” but not “someone”.

Here is a solution I created for that prob
<?
$var = "somesomesome somesome some, some. someone .some ";
$badword = "some";
$var = preg_replace(array("/([\W]+){$badword}([\W]+)/","/([\W]+){$badword}([\W]+)/"),"$1".str_repeat("*",strlen($badword))."$2",$var);
echo $var;
?>

5 replies on “Replace bad words in a string”

hehe … Hasin if you know russian language has so much badwords which must be censored … and simple array of badwords cannot help .. look at this pattern … russian antibadwords … cut out all badwords ;)))

$pattern = “/w{0,5}[хx]([хxs!@#$%^&*+-|/]{0,6})[уy]([уys!@#$%^&*+-|/]{0,6})[ёiлeеюийя]w{0,7}|w{0,6}[пp]([пps!@#$%^&*+-|/]{0,6})[iие]([iиеs!@#$%^&*+-|/]{0,6})[3зс]([3зсs!@#$%^&*+-|/]{0,6})[дd]w{0,10}|[сcs][уy]([уy!@#$%^&*+-|/]{0,6})[4чkк]w{1,3}|w{0,4}[bб]([bбs!@#$%^&*+-|/]{0,6})[lл]([lлs!@#$%^&*+-|/]{0,6})[yя]w{0,10}|w{0,8}[её][bб][лске@eыиаa][наи@йвл]w{0,8}|w{0,4}[еe]([еes!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]{0,6})[uу]([uуs!@#$%^&*+-|/]{0,6})[н4ч]w{0,4}|w{0,4}[еeё]([еeёs!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]{0,6})[нn]([нns!@#$%^&*+-|/]{0,6})[уy]w{0,4}|w{0,4}[еe]([еes!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]{0,6})[оoаa@]([оoаa@s!@#$%^&*+-|/]{0,6})[тnнt]w{0,4}|w{0,10}[ё]([ё!@#$%^&*+-|/]{0,6})[б]w{0,6}|w{0,4}[pп]([pпs!@#$%^&*+-|/]{0,6})[иeеi]([иeеis!@#$%^&*+-|/]{0,6})[дd]([дds!@#$%^&*+-|/]{0,6})[oоаa@еeиi]([oоаa@еeиis!@#$%^&*+-|/]{0,6})[рr]w{0,12}/i”;

oops .. wordpress wordwrap 🙁

$pattern = “/w{0,5}[хx]([хxs!@#$%^&*+-|/]{0,6})
[уy]([уys!@#$%^&*+-|/]{0,6})[ёiлeеюийя]
w{0,7}|w{0,6}[пp]([пps!@#$%^&*+-|/]
{0,6})[iие]([iиеs!@#$%^&*+-|/]{0,6})[3зс]
([3зсs!@#$%^&*+-|/]{0,6})[дd]w{0,10}|[сcs][уy]
([уy!@#$%^&*+-|/]{0,6})[4чkк]w{1,3}|w{0,4}[bб]
([bбs!@#$%^&*+-|/]{0,6})[lл]([lлs!@#$%^&*+-|/]
{0,6})[yя]w{0,10}|w{0,8}[её][bб][лске@eыиаa][наи@йвл]w{0,8}
|w{0,4}[еe]([еes!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]
{0,6})[uу]([uуs!@#$%^&*+-|/]{0,6})[н4ч]w{0,4}|w{0,4}
[еeё]([еeёs!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]
{0,6})[нn]([нns!@#$%^&*+-|/]{0,6})[уy]w{0,4}|w{0,4}[еe]
([еes!@#$%^&*+-|/]{0,6})[бb]([бbs!@#$%^&*+-|/]{0,6})
[оoаa@]([оoаa@s!@#$%^&*+-|/]{0,6})[тnнt]w{0,4}|w{0,10}[ё]
([ё!@#$%^&*+-|/]{0,6})[б]w{0,6}|w{0,4}[pп]
([pпs!@#$%^&*+-|/]{0,6})[иeеi]([иeеis!@#$%^&*+-|/]{0,6})
[дd]([дds!@#$%^&*+-|/]{0,6})[oоаa@еeиi]
([oоаa@еeиis!@#$%^&*+-|/]{0,6})[рr]w{0,12}/i”;

i wonder how this work .. but it’s WORKS !!!! :))

Leave a Reply to Sadia Cancel reply

Your email address will not be published. Required fields are marked *