Skip to content

Instantly share code, notes, and snippets.

@simonj
Last active November 21, 2016 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonj/a8ba8e988fcf5baa1be4801b49d63d17 to your computer and use it in GitHub Desktop.
Save simonj/a8ba8e988fcf5baa1be4801b49d63d17 to your computer and use it in GitHub Desktop.
Filter all bad words from array
<?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