@@ -13,6 +13,16 @@ class CensorWords
1313 */
1414 private $ censorChecks = null ;
1515
16+ /**
17+ * @var array
18+ */
19+ private $ whiteList = [];
20+
21+ /**
22+ * @var string
23+ */
24+ private $ whiteListPlaceHolder = ' {whiteList[i]} ' ;
25+
1626 public function __construct () {
1727 $ this ->badwords = array ();
1828 $ this ->replacer = '* ' ;
@@ -74,6 +84,43 @@ private function readBadWords($dictionary) {
7484 return array_values (array_unique ($ badwords ));
7585 }
7686
87+ /**
88+ * List of word to add which will be overridden
89+ *
90+ * @param array $list
91+ */
92+ public function addWhileList (array $ list )
93+ {
94+ foreach ($ list as $ value ) {
95+ if (is_string ($ value ) && !empty ($ value )) {
96+ $ this ->whiteList []['word ' ] = $ value ;
97+ }
98+ }
99+ }
100+
101+ /**
102+ * Replace white listed words with placeholders and inversely
103+ *
104+ * @param $string
105+ * @param bool $reverse
106+ * @return mixed
107+ */
108+ private function replaceWhiteListed ($ string , $ reverse = false )
109+ {
110+ foreach ($ this ->whiteList as $ key => $ list ) {
111+ if ($ reverse && !empty ($ this ->whiteList [$ key ]['placeHolder ' ])) {
112+ $ placeHolder = $ this ->whiteList [$ key ]['placeHolder ' ];
113+ $ string = str_replace ($ placeHolder , $ list ['word ' ], $ string );
114+ } else {
115+ $ placeHolder = str_replace ('[i] ' , $ key , $ this ->whiteListPlaceHolder );
116+ $ this ->whiteList [$ key ]['placeHolder ' ] = $ placeHolder ;
117+ $ string = str_replace ($ list ['word ' ], $ placeHolder , $ string );
118+ }
119+ }
120+
121+ return $ string ;
122+ }
123+
77124 /**
78125 * Sets the replacement character to use
79126 *
@@ -170,6 +217,7 @@ public function censorString($string, $fullWords = false) {
170217 $ match = array ();
171218 $ newstring = array ();
172219 $ newstring ['orig ' ] = html_entity_decode ($ string );
220+ $ original = $ this ->replaceWhiteListed ($ newstring ['orig ' ]);
173221 // $anThis for <= PHP5.3
174222 $ newstring ['clean ' ] = preg_replace_callback (
175223 $ this ->censorChecks ,
@@ -181,8 +229,9 @@ function($matches) use (&$anThis,&$counter,&$match) {
181229 ? str_repeat ($ anThis ->replacer , strlen ($ matches [0 ]))
182230 : $ anThis ->randCensor ($ anThis ->replacer , strlen ($ matches [0 ]));
183231 },
184- $ newstring [ ' orig ' ]
232+ $ original
185233 );
234+ $ newstring ['clean ' ] = $ this ->replaceWhiteListed ($ newstring ['clean ' ], true );
186235 $ newstring ['matched ' ] = $ match ;
187236
188237 return $ newstring ;
0 commit comments