【问题标题】:stripos from an external file?来自外部文件的条带?
【发布时间】:2022-01-06 13:45:37
【问题描述】:

我现在有这个代码:

if ((stripos($text,'badword1') !== false) ||
   (stripos($text,'badword2') !== false))
    {
blablabla
}

它检查 $text 中是否有一个坏词,并且效果很好。

问题是我有几个坏词,所以代码很长。

是否可以将所有的badwords放在一个外部文件中并检查它而不是把它全部放在php中?

谢谢。

按要求编辑,这是完整的代码。是 PHP 中的 Telegram 机器人:

if ((stripos($text,'badword') !== false))
    {
    $content = array(
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "messaggio cancellato",
'parse_mode' => 'HTML',
'disable_web_page_preview' => true
    );
    $telegram->sendMessage($content);
    $telegram->deleteMessage($content);
    }

我尝试了建议的解决方案之一,但它不起作用,如下所示:

$blacklist = "blacklist.txt";
$contents = file_get_contents($blacklist);
$lines = explode("\n", $contents);

if ((stripos($text,$lines) !== false))
    {
    $content = array(
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "messaggio cancellato",
'parse_mode' => 'HTML',
'disable_web_page_preview' => true
    );
    $telegram->sendMessage($content);
    $telegram->deleteMessage($content);
    }

【问题讨论】:

  • 是的,这是可能的。为什么不试试看会发生什么?
  • 我已经尝试了很长时间,但我无法弄清楚如何制作它。例如,我尝试使用 $filename = 'blacklist.txt'; if ((stripos(($text,file_get_contents($filename)) !== false)) 但它不起作用。
  • 这取决于文件的结构。请通过编辑将所有尝试添加到您的问题中。我假设您需要遍历该文件的所有行
  • 根据字数,你可以explode into an array and loop或者使用效率更高的东西,比如SplFileObject
  • this 之类的内容可能有助于解决您的问题。

标签: php arrays string


【解决方案1】:

在另一个文件中创建包含坏词的数组

// words.php
$words = ["word_1", "word_2", "word_3", "word_4"] // as many words as you need

接下来,创建您的工作文件并调用您的文字文件:

// file.php
require "words.php";

function strposa($haystack, $needles=array(), $offset=0) {
    $chr = array();
    foreach($needles as $needle) {
            $res = strpos($haystack, $needle, $offset);
            if ($res !== false) $chr[$needle] = $res;
    }
    if(empty($chr)) return false;
    return min($chr);
}

$string = 'Some text that word_1 contain some bad words';

if (strposa($string, $words)) {
    echo 'true';
} else {
    echo 'false';
}

这里我使用的是strpos with array,功能很小,代码看起来很干净

【讨论】:

  • 谢谢,我认为这会起作用,但我正在尝试制作一个 .txt 文件来读取,而不是另一个带有变量的 PHP 文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2013-02-06
  • 2016-07-09
  • 2017-08-09
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多