我想创建一个小脚本,将采取在用户输入的文本,然后搜索文本中的坏词。坏单词在数组中定义。就我所得到的,我应该有以下的过程:
- 从用户获取输入——这部分很简单,使用$_POST数组
- 将输入的字符串转换为数组-使用explosion()函数
- 创建2个for循环,1个外部for循环和1个内部for循环。在内部for循环中,创建一个if语句来检查坏单词。
我希望每次找到一个坏单词时,它将增加变量,该变量将计算坏单词的总数。
我设法编码所有这些,但我的计数器不工作,因为它应该,它给我0。
代码如下:
<?php
$badWordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = strtolower($inputedText);
$inputedText_ToProcess = explode(" ", $inputedText_ToProcess);
$outerLoop = sizeof($inputedText_ToProcess);
$innerLoop = sizeof($badWords);
for ($a = 0; $a < $outerLoop ; $a++)
{
for ($b = 0; $b < $innerLoop; $b++)
{
if ($badWords[$b] == $inputedText_ToProcess[$a])
{
$badwordCounter = $badWordCounter + 1;
}
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: $badWordCounter</p>";
echo "The entered text string is: $inputedText";
?>
注意变量的大小写:
$bad**w**ordCounter = $badWordCounter + 1;
由于嵌套循环过于复杂,一个更简洁的例子:
<?php
$_POST['inputText'] = 'come on you ass hole!'; // hardcoded for testing
$badwordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = strtolower($inputedText);
$inputedText_ToProcess = explode(" ", $inputedText_ToProcess);
// Iterate through each word
foreach ($inputedText_ToProcess as $word) {
// If that word exists in the badWords array
if (in_array($word, $badWords)) {
$badwordCounter++;
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: $badwordCounter</p>";
echo "The entered text string is: $inputedText";
可以使用foreach遍历整个数组。比for循环简单。此外,还有一个名为in_array的函数,用于检查作为第一个参数给出的字符串是否在作为第二个参数给出的数组中。所以这个应该可以用:
<?php
$badWordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = explode(" ", $inputedText);
foreach ($inputedText_ToProcess as $value) {
if (in_array(strtolower($value), $badWords)) {
$badWordCounter++;
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: " . $badWordCounter . "</p>";
echo "The entered text string is: " . $inputedText;
?>
你在变量badWordCounter中添加Word的大写字母时忘记了。
应该是:
$badWordCounter = $badWordCounter + 1;
代替:
$badwordCounter = $badWordCounter + 1;
你也可以用$badWordCounter++;
既然每个人都发布了其他不起作用的代码,我想我应该提供一个更简单的解决方案,并使用标点符号:
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
preg_match_all("/".implode('|', $badWords)."/i", $_POST['inputText'], $badWordCounter);
echo '<p>The Total Number of Bad Words Detected In The Text: '.count($badWordCounter[0]).'</p>';
echo 'The entered text string is: '.$_POST['inputText'];