Last active
November 21, 2016 12:47
-
-
Save simonj/a8ba8e988fcf5baa1be4801b49d63d17 to your computer and use it in GitHub Desktop.
Filter all bad words from array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BadWordFilter | |
{ | |
/** | |
* @var array | |
**/ | |
public $badWords = ['fuck', 'idiot']; | |
/** | |
* Replace bad words | |
* | |
* @param $text | |
* | |
* @return mixed | |
**/ | |
public function filter($text) | |
{ | |
// Collect all words been pushed. | |
$replacedWord = []; | |
foreach ($text as $badWord) { | |
// Option 1. | |
// Get Length of word to add right number of stars(***). | |
$length = strlen($badWord); | |
// Show first character and change last characters to stars(***). | |
$newWord = substr($badWord, 0, 1) . str_repeat('*', $length - 1); | |
// option 2. | |
// Show first character and change last characters to stars(***). | |
// $newWord = preg_replace('/(?!^)\S/', '*', $badWord); | |
array_push($replacedWord, $newWord); | |
} | |
return $replacedWord; | |
} | |
} | |
$words = (new BadWordFilter()); | |
var_dump($words->filter($words->badWords)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment