检查文本是否包含PHP中txt文件中的单词

检查文本是否包含PHP中txt文件中的单词,php,arrays,text,Php,Arrays,Text,我的目标是检查我在文本框中键入的内容是否与列表中的任何单词匹配。我的列表在一个.txt文件中。我想我应该将.txt转换成一个数组,并将它的值与另一个数组进行比较,这个数组来自文本框表单。我认为应该将.txt文件中的文本放入一个数组中,但这种比较不太有效 可能是这样的: $count = 0; If ($textbox contains $anyofthewordsfromthe.txt file) echo "Name of the words:" $numberofocurrences. E

我的目标是检查我在文本框中键入的内容是否与列表中的任何单词匹配。我的列表在一个.txt文件中。我想我应该将.txt转换成一个数组,并将它的值与另一个数组进行比较,这个数组来自文本框表单。我认为应该将.txt文件中的文本放入一个数组中,但这种比较不太有效

可能是这样的:

$count = 0;
If ($textbox contains $anyofthewordsfromthe.txt file)
 echo "Name of the words:" $numberofocurrences.
Else
  echo "No words from the list!"

谢谢大家!!节日快乐

您可以在线执行或从页面复制代码


你是怎么比较的?
您可以将单词放入数组,然后与in_array进行比较,首先将单词列表作为数组加载,使用file_get_内容,然后使用explode或preg_match_all。然后检查消息中的每个单词是否在列表中,反之亦然。您可以使用strpos查找邮件中的每个单词,如果斯肯索普在邮件中,它将找到索普。或者,您也可以将消息拆分为单词,并在列表中查找每个单词,这将忽略虚假的子字符串。以下命令行PHP脚本显示了这两种方法:

<?php

// Like explode() but uses any sequence of spaces as delimiter.
// Equivalent to Python s.split()
function explode_space($s) {
  preg_match_all('/[^\s]+/', $s, $words);
  return $words[0];
}

$swears_filename = 'words.txt';

// Load all words from the file
$swears = strtolower(file_get_contents($swears_filename));
$swears = explode_space($swears);

// In a web environment, it'd probably be more like this:
// $naughty_text = trim(@$_POST['comment']);
$naughty_text = 'I tweeted about passing the third rep milestone on Stack Overflow.';

// Perform case-insensitive comparison by lowercasing everything first.
$naughty_text = strtolower($naughty_text);

// There are two solutions. The first uses substring matching,
// which finds "thorpe" in "Scunthorpe" if "thorpe" is in words.txt.
foreach ($swears as $swear) {
  if (strpos($naughty_text, $swear) !== false) {
    echo "Text contains substring $swear\n";
  }
}

// The other solution will find "Scunthorpe" only if "scunthorpe"
// itself is in words.txt because it checks the whole word.
// First convert the list of values to a set of keys to speed up
// testing whether each word is in the set because
// array_key_exists($k, $array), which looks for keys, is
// faster than in_array($v, $array), which looks for values.
$swears = array_fill_keys($swears, true);

// Now convert the post to a list of distinct words.
$naughty_text = explode_space($naughty_text);

foreach ($naughty_text as $word) {
  if (array_key_exists($word, $swears)) {
    echo "Text contains word $word\n";
  }
}

你的文本文件中有多少个单词???用谷歌搜索你问题的标题。你一定会找到什么,我百分之百肯定。你试过什么?向我们展示一些您尝试过但不起作用的代码。
$ cat words.txt
slit pass puck cult locksacker monkeyfighter hits part third tweet
$ php so27629576.php
Text contains substring pass
Text contains substring third
Text contains substring tweet
Text contains word third