PHP: checking and replacing files with an array

I have this code that must first process the entire word file in the array, and then check the string passed for any of these words in the file. if a match, then replace with *.

the file looks something like this:

wordalex wordjordan wordjohn .... 

Unfortunately, the proposal I submitted is not filtered in the mod I expect. Nothing really happens to him. Could you familiarize yourself with the given code and help.

 $comment = "the wordalex if this doesn't get caught!"; $filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES); //print_r($filterWords); $textToPrint = filterwords($comment,$filterWords ); echo $textToPrint; function filterwords($text, $filterArray){ $filterCount = sizeof($filterWords); for($i=0; $i<$filterCount; $i++){ $text = preg_replace('/\b'.$filterWords[$i].'\b/ie',"str_repeat('*',strlen('$0'))",$text); } return $text; } 

therefore, in the original sentence there are bard words, but deleted for the purpose of publication.

thanks

+4
source share
2 answers

In the function definition, you call the list of words $filterArray .

 function filterwords($text, $filterArray){ 

But in all of your function, you call it $filterWords .

Rename it in $filterWords to a definition or rename each entry in $filterArray .

+2
source

Build $filterWords , ignoring empty lines. You really need both FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES

 $filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 

Assembly of spare arrays:

 $replacements = array(); $patterns = array(); foreach ($filterWords as $word) { // ignore empty words, just in case if (empty($word)) continue; $replacements[] = str_repeat('*', strlen($word)); $patterns[] = "/\b$word\b/i"; } 

And then do preg_replace() :

 $textToPrint = preg_replace($patterns, $replacements, $comment); 

This will give Hello ******** NOTwordjohn from Hello wordJoHN NOTwordjohn .

+1
source

All Articles