如何从php中的字符串中只获取一定数量的单词? [英] How do I get only a determined number of words from a string in php?

查看:107
本文介绍了如何从php中的字符串中只获取一定数量的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



我将全面沉浸在PHP,我不熟悉许多字符串函数,但。

在此先感谢,
Jason

解决方案

会建议不要将字数作为基准。您可能会轻易地以 多个数据。过去使用的是要求一个期望的长度,但要确保它不会截断一个单词。这里有一些可能适合你的东西:

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

返回$ text;
}

也就是说,如果您传递 1 作为 str_word_count 的第二个参数,它将返回一个包含所有单词的数组,并且您可以对该数组使用数组操作。
另外,你可以 ,但它有点hackey,爆炸空间上的字符串等......但是,这引入了很多错误的空间,例如,字。



PS。如果您需要上述函数的Unicode安全版本,并且安装了 mbstring 图标v 扩展名,则只需替换所有字符串函数都带有它们的 mb _ iconv _ 前缀对等项。


Here is what I am trying to do. I have a block of text and I would like to extract the first 50 words from the string without cutting off the words in the middle. That is why I would prefer words opposed to characters, then I could just use a left() function.

I know the str_word_count($var) function will return the number of words in a string, but how would I return only the first 50 words?

I'm going full immersion on PHP and I'm not familiar with many of the string functions, yet.

Thanks in advance, Jason

解决方案

I would recommend against using the number of words as a baseline. You could easily end up with much less or much more data than you intended to display.

One approach I've used in the past is to ask for a desired length, but make sure it does not truncate a word. Here's something that may work for you:

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

    return $text;
}

That said, if you pass 1 as the second parameter to str_word_count, it will return an array containing all the words, and you can use array manipulation on that. Also, you could although, it's somewhat hackey, explode the string on spaces, etc... But that introduces lots of room for error, such as things that are not words getting counted as words.

PS. If you need a Unicode safe version of the above function, and have either the mbstring or iconv extensions installed, simply replace all the string functions with their mb_ or iconv_ prefixed equivalents.

这篇关于如何从php中的字符串中只获取一定数量的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆