【问题标题】:Seeing if a text file contains a word in php查看文本文件是否包含php中的单词
【发布时间】:2014-04-02 13:38:21
【问题描述】:

我想查看一个字符串,看看字符串中的任何单词是否与文本文件中的单词匹配。

假设我有一个 product.txt 文件,它包含:

苹果 索尼 戴森 麦当劳 iPod

这是我的代码:

    <?php

$productFile = file_get_contents('products.txt', FILE_USE_INCLUDE_PATH);

/*
* product.txt file contains
* apple
* pc
* ipod
* mcdonalds
*/

$status = 'i love watching tv on my brand new apple mac';

    if (strpos($status,$productFile) !== false) {
        echo 'the status contains a product';
    }

    else{
        echo 'The status doesnt contain a product';
    }

?>

现在它告诉我状态不包含它所包含的产品,任何人都可以看到我哪里出错了吗?

【问题讨论】:

    标签: php text-files


    【解决方案1】:

    您正在整个字符串中搜索单词列表。相反,您必须单独搜索单词列表中的每个单词。例如,str_word_count 可用于将字符串拆分为单词。

    <?php
    
    $productFile = file_get_contents('products.txt');
    $products = str_word_count($productFile, 1);
    
    $status = 'i love watching tv on my brand new apple mac';
    
    $found = false;
    foreach ($products as $product)
    {
        if (strpos($status,$product) !== false) {
            $found = true;
            break;
        }
    }
    
    if ($found) {
        echo 'the status contains a product';
    }
    else {
        echo 'The status doesnt contain a product';
    }
    
    ?>
    

    您可能还想考虑使用stripos 而不是strpos 进行不区分大小写的比较。

    【讨论】:

      【解决方案2】:
      <?php
      
      $productFile = file_get_contents('products.txt', FILE_USE_INCLUDE_PATH);
      
      /*
      * product.txt file contains
      * apple
      * pc
      * ipod
      * mcdonalds
      */
      
      $status = 'i love watching tv on my brand new apple mac';
      $status = str_replace(' ', '|', $status);
      
      if ( preg_match('/'.$status.'/m',$productFile) ) {
          echo 'the status contains a product';
      }
      else {
          echo 'The status doesnt contain a product';
      }
      

      【讨论】:

        【解决方案3】:

        首先,我认为你混淆了变量顺序(Reference

        mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
        

        然后您必须手动检查每个单词,文件中不存在整个字符串,只有一个单词存在。例如,使用explode() 创建一个数组并使用foreach 循环。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-28
          • 1970-01-01
          • 1970-01-01
          • 2018-01-24
          • 1970-01-01
          • 1970-01-01
          • 2013-12-29
          相关资源
          最近更新 更多