如何从php中的字符串中仅获取确定数量的单词?

时间:2009-07-11 04:25:57

标签: php string function

这是我想要做的。我有一个文本块,我想从字符串中提取前50个单词而不切断中间的单词。这就是为什么我更喜欢与字符相对的词,然后我可以使用left()函数。

我知道str_word_count($ var)函数会返回字符串中的单词数,但是如何只返回前50个单词呢?

我完全沉浸在PHP中,但我还不熟悉许多字符串函数。

提前致谢, 杰森

6 个答案:

答案 0 :(得分:15)

我建议不要使用单词数作为基线。您可以轻松地使少或多于您想要显示的数据。

我过去使用的一种方法是要求所需的长度,但要确保它不会截断一个单词。这可能适合您:

function function_that_shortens_text_but_doesnt_cutoff_words($text, $length)
{
    if(strlen($text) > $length) {
        $text = substr($text, 0, strpos($text, ' ', $length));
    }

    return $text;
}

也就是说,如果将1作为第二个参数传递给str_word_count,它将返回一个包含所有单词的数组,并且可以对其使用数组操作。 此外,你可能虽然,它有点hackey,爆炸空间等字符串...但是这会引入很多错误的空间,例如那些不被视为单词的单词。

PS。如果您需要上述函数的Unicode安全版本,并且安装了mbstringiconv扩展名,只需将所有字符串函数替换为mb_iconv_前缀等同物。

答案 1 :(得分:9)

str_word_count采用一个可选参数,告诉它返回什么。

返回字符串数组:

$words = str_word_count($var, 1);

然后你可以用以下内容来解决问题:

$len = min(50, count($words));
$first_fifty = array_slice($words, 0, $len);

答案 2 :(得分:2)

你确定要一定数量的单词吗?如果您正在做类似“预览”的事情,通常最好做一些类似“最多300个字符,在字边界切断”的内容,在这种情况下,您可以使用类似的内容:

if (strlen($str)>300)
{
  $str = substr($str,0,300);
  $pos = strrpos($str, ' ');
  if ($pos !== false && $pos > 200) // If there is no space in the last 100 chars, just truncate
    $str = substr($str,0,$pos);
  // You may also want to add ellipses:
  // $str .= '...';
}

答案 3 :(得分:2)

我找到了更简单的方法:

function get_len_of_word($str,$number) { $array_str = explode(" ", $str); if(isset($array_str[$number])) { return implode(" ",array_slice($array_str, 0, $number)); } return $str; }

答案 4 :(得分:1)

这是另一个例子,

function getWordsFromString($str,$word_count)
{
    $new_str=$str;
    $_strArr=explode(" ",$str);
    $_tempArr=array();
    if(count($_strArr)>$word_count) 
    {
        foreach ($_strArr as $key=> $value) {
            $_tempArr[]=$value; 
            if($key==$word_count-1)
            {
                $new_str=implode(" ",$_tempArr).' ...';
            }
        }   
    }
    return $new_str;
} 

答案 5 :(得分:0)

    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);

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