我们怎么能分开一个句子

时间:2010-12-02 16:55:40

标签: php

我编写了用于获取给定动态句子的某些部分的PHP代码,例如"this is a test sentence"

substr($sentence,0,12);

我得到了输出:

this is a te

但是我需要它作为一个完整的词而不是分裂一个词:

this is a

我怎么能这样做,记住$sentence不是一个固定的字符串(它可以是任何东西)?

6 个答案:

答案 0 :(得分:3)

使用wordwrap

答案 1 :(得分:3)

如果您使用的是PHP4,则可以使用split

$resultArray = split($sentence, " ");

数组的每个元素都是一个单词。但要注意标点符号。

explode将是PHP5中推荐的方法:

$resultArray = explode(" ", $sentence);

答案 2 :(得分:2)

第一。在空间上使用爆炸。然后,计算每个部分+总组装字符串,如果没有超过限制,则将其连接到带有空格的字符串上。

答案 3 :(得分:1)

尝试使用explode()功能。

在你的情况下:

$expl = explode(" ",$sentence);

你会把你的句子放在一个数组中。第一个单词是$ expl [0],第二个单词是$ expl [1],依此类推。要在屏幕上打印出来,请使用:

$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
  print $expl[$i]." ";
}

答案 4 :(得分:0)

这只是伪代码而不是php,

char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}

新构造的句子就是你想要的!!!

答案 5 :(得分:0)

创建一个可以随时重复使用的功能。如果给定字符串的长度大于您想要修剪的字符数,这将查找最后一个空格。

function niceTrim($str, $trimLen) {
    $strLen = strlen($str);
    if ($strLen > $trimLen) {
        $trimStr = substr($str, 0, $trimLen);
        return substr($trimStr, 0, strrpos($trimStr, ' '));
    }
    return $str;
}

$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);

这将打印

this is a

根据需要。

希望这是您正在寻找的解决方案!

相关问题