获取字符串的前 N 个单词

问题描述 投票:0回答:13

如何仅获取字符串中的前 10 个单词?

php string substring trim truncate
13个回答
140
投票
implode(' ', array_slice(explode(' ', $sentence), 0, 10));

要添加对逗号和破折号等其他断词的支持,

preg_match
提供了一种快速方法,不需要拆分字符串:

function get_words($sentence, $count = 10) {
  preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
  return $matches[0];
}

正如 Pebbl 提到的,PHP 不能很好地处理 UTF-8 或 Unicode,所以如果这是一个问题,那么您可以将

\w
替换为
[^\s,\.;\?\!]
,将
\W
替换为
[\s,\.;\?\!]


54
投票

如果句子结构中存在意外字符代替空格,或者句子包含多个相连的空格,则仅按空格分割将无法正确运行。

无论您在单词之间使用哪种“空格”,以下版本都可以工作,并且可以轻松扩展以处理其他字符...它目前支持任何空白字符加上 , 。 ; ? !

function get_snippet( $str, $wordCount = 10 ) {
  return implode( 
    '', 
    array_slice( 
      preg_split(
        '/([\s,\.;\?\!]+)/', 
        $str, 
        $wordCount*2+1, 
        PREG_SPLIT_DELIM_CAPTURE
      ),
      0,
      $wordCount*2-1
    )
  );
}

正则表达式非常适合解决这个问题,因为您可以轻松地使代码变得灵活或严格,如您所愿。不过,你必须要小心。我专门针对单词之间的间隙(而不是单词本身)来处理上述内容,因为很难明确地说明单词的定义。

采用

\w
单词边界,或其反面
\W
。我很少依赖这些,主要是因为 - 取决于您使用的软件(例如某些版本的 PHP) - 它们并不总是包含 UTF-8 或 Unicode 字符

在正则表达式中,最好始终保持具体。这样你的表达式就可以处理如下的事情,无论它们在哪里渲染:

echo get_snippet('Это не те дроиды, которые вы ищете', 5);

/// outputs: Это не те дроиды, которые

然而,就性能而言,避免分裂可能是值得的。因此,您可以使用 Kelly 的更新方法,但将

\w
切换为
[^\s,\.;\?\!]+
,将
\W
切换为
[\s,\.;\?\!]+
。虽然我个人喜欢上面使用的分割表达式的简单性,但它更容易阅读和修改。然而 PHP 函数的堆栈有点丑陋:)


7
投票

http://snipplr.com/view/8480/a-php-function-to-return-the-first-n-words-from-a-string/

function shorten_string($string, $wordsreturned)
{
    $retval = $string;  //  Just in case of a problem
    $array = explode(" ", $string);
    /*  Already short enough, return the whole thing*/
    if (count($array)<=$wordsreturned)
    {
        $retval = $string;
    }
    /*  Need to chop of some words*/
    else
    {
        array_splice($array, $wordsreturned);
        $retval = implode(" ", $array)." ...";
    }
    return $retval;
}

3
投票

我建议使用

str_word_count
:

<?php
$str = "Lorem ipsum       dolor sit    amet, 
        consectetur        adipiscing elit";
print_r(str_word_count($str, 1));
?>

上面的例子将输出:

Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet
    [5] => consectetur
    [6] => adipiscing
    [7] => elit
)

使用循环来获取你想要的单词。

来源:http://php.net/str_word_count


2
投票

要选择给定文本的 10 个单词,您可以实现以下功能:

function first_words($text, $count=10)
{
    $words = explode(' ', $text);

    $result = '';
    for ($i = 0; $i < $count && isset($words[$i]); $i++) {
        $result .= $words[$i];
    }

    return $result;
}

2
投票

这可以使用

str_word_count()

轻松完成
$first10words = implode(' ', array_slice(str_word_count($sentence,1), 0, 10));

1
投票

这可能对你有帮助。返回 N 号的函数。字数

public function getNWordsFromString($text,$numberOfWords = 6)
{
    if($text != null)
    {
        $textArray = explode(" ", $text);
        if(count($textArray) > $numberOfWords)
        {
            return implode(" ",array_slice($textArray, 0, $numberOfWords))."...";
        }
        return $text;
    }
    return "";
    }
}

1
投票

试试这个

$str = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
 $arr = explode(" ", str_replace(",", ", ", $str));
 for ($index = 0; $index < 10; $index++) {
 echo $arr[$index]. " ";
}

我知道现在不是回答的时候,但让新人选择自己的答案。


1
投票
    function get_first_num_of_words($string, $num_of_words)
    {
        $string = preg_replace('/\s+/', ' ', trim($string));
        $words = explode(" ", $string); // an array

        // if number of words you want to get is greater than number of words in the string
        if ($num_of_words > count($words)) {
            // then use number of words in the string
            $num_of_words = count($words);
        }

        $new_string = "";
        for ($i = 0; $i < $num_of_words; $i++) {
            $new_string .= $words[$i] . " ";
        }

        return trim($new_string);
    }

像这样使用它:

echo get_first_num_of_words("Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, illo?", 5);

输出:

Lorem ipsum dolor sit amet

此功能对于阿拉伯字符等 unicode 字符也非常有效。

echo get_first_num_of_words("نموذج لنص عربي الغرض منه توضيح كيف يمكن استخلاص أول عدد معين من الكلمات الموجودة فى نص معين.", 100);

输出:

نموذج لنص عربي الغرض منه توضيح كيف يمكن استخلاص أول عدد معين من الكلمات الموجودة فى نص معين.


0
投票

这正是我们正在寻找的 只需剪切并粘贴到您的程序中即可运行。

function shorten_string($string, $wordsreturned)
/*  Returns the first $wordsreturned out of $string.  If string
contains fewer words than $wordsreturned, the entire string
is returned.
*/
{
$retval = $string;      //  Just in case of a problem

$array = explode(" ", $string);
if (count($array)<=$wordsreturned)
/*  Already short enough, return the whole thing
*/
{
$retval = $string;
}
else
/*  Need to chop of some words
*/
{
array_splice($array, $wordsreturned);
$retval = implode(" ", $array)." ...";
}
return $retval;
}

只需调用代码块中的函数即可,就像

一样
$data_itr = shorten_string($Itinerary,25);

0
投票

我这样做:

function trim_by_words($string, $word_count = 10) {
    $string = explode(' ', $string);
    if (empty($string) == false) {
        $string = array_chunk($string, $word_count);
        $string = $string[0];
    }
    $string = implode(' ', $string);
    return $string;
}

其UTF8兼容...


0
投票

这可能对你有帮助。返回 10

no. of words
.

的函数
function num_of_word($text,$numb) {
 $wordsArray = explode(" ", $text);
 $parts = array_chunk($wordsArray, $numb);

 $final = implode(" ", $parts[0]);

 if(isset($parts[1]))
     $final = $final." ...";
 return $final;
 return;
 }
echo num_of_word($text, 10);

0
投票

不是生成一个包含 N 个单词的数组,然后截断数组,然后重新内爆单词,而是截断第 N 个单词之后的输入字符串。 演示

echo preg_replace('/(?:\s*\S+){10}\K.*/', '', $string);

该模式将搜索 N 个由零个或多个空白字符组成的序列,后跟一个或多个非空白字符,然后

\K
重新启动全字符串匹配(有效地“释放”匹配字符,然后
.*
将匹配其余的字符)字符串。无论匹配到什么,都会被替换为空字符串。

此解决方案将确保输出字符串不超过 N 个单词。该字符串的单词数可能少于 N,因此请注意,不会发生任何突变,并且如果该字符串有尾随空格,则该空格将不会被删除。

为了确保删除前导和空格,请调整模式以捕获由空格分隔的 0 到 N 个单词。 演示

$string = '    I would like to know   ';

var_export(
    preg_replace('/\s*(\S*(?:\s+\S+){0,9}).*/', '$1', $string)
);
© www.soinside.com 2019 - 2024. All rights reserved.