Created
January 14, 2018 19:07
-
-
Save m3g4p0p/f33f938decfa4a232bd4ab4d511060a9 to your computer and use it in GitHub Desktop.
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 | |
if (isset($_POST['comment'])) { | |
echo replaceWords($_POST['comment']); | |
} else { | |
echo renderForm(); | |
} | |
function replaceWords($comment) { | |
$bad_words = ['fuck', 'shit', 'pussy']; | |
$pattern = array_map(function($word) { | |
$first = substr($word, 0, 1); | |
$middle = substr($word, 1, -1); | |
$last = substr($word, -1); | |
return "/\b($first)$middle($last)\b/i"; | |
}, $bad_words); | |
return preg_replace($pattern, '$1***$2', $comment); | |
} | |
function renderForm() { | |
return <<<HTML | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Bad words</title> | |
</head> | |
<body> | |
<form id="my-form"> | |
<textarea name="comment" id="comment"></textarea> | |
</form> | |
<pre id="result"></pre> | |
<script> | |
const form = document.getElementById('my-form') | |
const message = document.getElementById('comment') | |
const result = document.getElementById('result') | |
message.addEventListener('input', () => { | |
const data = new FormData(form) | |
const xhr = new XMLHttpRequest() | |
xhr.onload = () => { | |
result.textContent = xhr.responseText | |
} | |
xhr.open('POST', 'validate.php') | |
xhr.send(data) | |
}) | |
</script> | |
</body> | |
</html> | |
HTML; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment