Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

arrays - How to Replace Bad Words in a Comment with Asterisks Using PHP


Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

<?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("
", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String <br> $input_string <br><br><hr><br>Input String Fixed <br> $fixed";
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There might be cases where whitespace is appended to the array element($abusive_words) while retrieving it from the text file. str_ireplace() might not be able to get perfect match due to these whitespaces. So its always better to trim the array elements before proceeding further especially for comparison.

array_map() and trim is what you need.

$abusive_words = array_map('trim', $abusive_words);

Do this before passing array to str_ireplace()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...