【问题标题】:How to get the first n words from text stored in my DB in PHP?如何从 PHP 中存储在我的数据库中的文本中获取前 n 个单词?
【发布时间】:2010-06-10 10:36:39
【问题描述】:

我需要知道如何从 PHP 中存储在我的数据库中的文本中获取前 n 个单词?

例如,如果我的数据库中有这样的文本:

"word1 word2 word3 word4 text 一测四五"

我怎样才能得到这篇文章的前 4 或 5 个单词?

【问题讨论】:

    标签: php mysql string


    【解决方案1】:

    使用 MySQL SUBSTRING INDEX 函数。

    -- Will select everything up until the fifth space.
    SELECT SUBSTRING_INDEX(YourTextField, ' ', 5); 
    

    【讨论】:

      【解决方案2】:

      您可以使用explode函数将字符串按空格分割并获取每个单词:

      $words = 'word1 word2 word3 word4 text one test four five';
      $words_array = explode(' ', $words);
      

      然后你可以使用 array_chunk 函数来获取字数:

      print_r(array_chunk($words_array, 4, true));
      

      【讨论】:

        【解决方案3】:

        因为拥有一个正则表达式总是很不错的:

        if (preg_match('/([^\\s]*(?>\\s+|$)){0,4}/', $string, $matches)) {
            //result in $matches[0]
        }
        

        【讨论】:

          猜你喜欢
          • 2014-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-23
          • 2016-01-10
          • 2017-05-09
          相关资源
          最近更新 更多