@@ -13,6 +13,16 @@ class CensorWords
13
13
*/
14
14
private $ censorChecks = null ;
15
15
16
+ /**
17
+ * @var array
18
+ */
19
+ private $ whiteList = [];
20
+
21
+ /**
22
+ * @var string
23
+ */
24
+ private $ whiteListPlaceHolder = ' {whiteList[i]} ' ;
25
+
16
26
public function __construct () {
17
27
$ this ->badwords = array ();
18
28
$ this ->replacer = '* ' ;
@@ -74,6 +84,43 @@ private function readBadWords($dictionary) {
74
84
return array_values (array_unique ($ badwords ));
75
85
}
76
86
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
+
77
124
/**
78
125
* Sets the replacement character to use
79
126
*
@@ -170,6 +217,7 @@ public function censorString($string, $fullWords = false) {
170
217
$ match = array ();
171
218
$ newstring = array ();
172
219
$ newstring ['orig ' ] = html_entity_decode ($ string );
220
+ $ original = $ this ->replaceWhiteListed ($ newstring ['orig ' ]);
173
221
// $anThis for <= PHP5.3
174
222
$ newstring ['clean ' ] = preg_replace_callback (
175
223
$ this ->censorChecks ,
@@ -181,8 +229,9 @@ function($matches) use (&$anThis,&$counter,&$match) {
181
229
? str_repeat ($ anThis ->replacer , strlen ($ matches [0 ]))
182
230
: $ anThis ->randCensor ($ anThis ->replacer , strlen ($ matches [0 ]));
183
231
},
184
- $ newstring [ ' orig ' ]
232
+ $ original
185
233
);
234
+ $ newstring ['clean ' ] = $ this ->replaceWhiteListed ($ newstring ['clean ' ], true );
186
235
$ newstring ['matched ' ] = $ match ;
187
236
188
237
return $ newstring ;
0 commit comments