代码之家  ›  专栏  ›  技术社区  ›  Sagar Gautam

如何在PHP中从包含完整句子的文本中获取特定单词?

  •  1
  • Sagar Gautam  · 技术社区  · 6 年前

    我想从课文中得到一些句子。

    示例文本如下:,

    到目前为止,我所做的是我能从一篇大文章中得到30个单词,但最后,我得到了一个不完整的句子,我想删除这样的句子。

    下面是获取30个单词的函数,

    /**
     * @param $sentence
     * @param int $count
     * @return mixed
     */
    function get_words($sentence, $count = 30) {
        preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
        return $matches[0];
    }
    

    我使用了下面问题中的上述函数

    How to select first 10 words of a sentence?

    当我将上面的文本传递给函数时,我得到如下输出,

    这里的最后一句话是不完整的,我不希望在我的输出这样。

    有没有办法做到这一点?

    我正在与PHP和Laravel合作,欢迎提供任何帮助和建议。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ramya    6 年前

    下面的代码可能对您有所帮助。

    <?php
    $sen="Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.";
    $cropped_data =  get_words($sen);
    $strlength = strlen ( $cropped_data );
    $remains=  complete_sentence(substr($sen,$strlength));
    
    function complete_sentence($content) {
        $pos = strpos($content, '.');
        return substr($content, 0, $pos+1);
    }
    
    function get_words($sentence, $count = 30) {
        preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
        return $matches[0];
    }
    
    echo "complete sentence<br/>".$cropped_data.$remains;
    ?>
    

        2
  •  0
  •   Md.Sukel Ali    6 年前
    function get_words($sentence, $count = 30) {
    
      preg_match("/(?:w+(?:W+|$)){0,$count}/", $sentence, $matches);
    
      return $matches[0];
    };
    
    $sentence = "Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.";
    
    $cropSentence =  get_words($sentence);
    
    $finalSentence= substr($cropSentence, 0, strrpos($cropSentence, "."));
    echo $finalSentence;
    

    它将返回到最后一次出现(.);

    鹰头狮低声打断了他的话“一点也不,”渡渡鸟说, 指着树林里杂乱的喧闹声——(她认为他是 但是你