먼저 부하 배열로서 단어의 목록과 비교를 다음 배열에 포함 된 단어를 넣고있다. 그런 다음 메시지의 각 단어가 목록에 있는지 또는 그 반대인지 확인하십시오. strpos()
을 사용하여 메시지의 각 단어를 찾을 수 있습니다. "Scunthorpe"가 메시지에 있으면 "thorpe"를 찾습니다. 또는 메시지를 단어로 나눌 수 있으며 목록에서 각 단어를 찾아 볼 수 있습니다. 그러면 가짜 하위 문자열이 무시됩니다. 다음 명령 줄 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
??? – user3750649
Google에 질문의 제목을 입력하십시오. 너는 뭔가를 찾을 의무가있어, 나는 그것의 100 % 확실하다. –
무엇을 시도 했습니까? 시도하고 작동하지 않는 코드를 보여주십시오. –