如何只保存字符串中的前4个单词?

时间:2013-09-20 00:25:24

标签: php string explode implode

所以基本上我是一个非常大的字符串,我只想保存它的前4个字。

我几乎已经有了这个工作,虽然有些情况会破坏它。

这是我目前的代码:

$title = "blah blah blah, long paragraph goes here";
//Make title only have first 4 words
$pieces = explode(" ", $title);
$first_part = implode(" ", array_splice($pieces, 0, 4));
$title = $first_part;
//title now has first 4 words

打破它的主要案例是line-breaks。如果我有这样的段落:

Testing one two three
Testing2 a little more three two one

$title等于Testing one two three Testing2

另一个例子:

Testing
test1
test2
test3
test4
test5
test6
sdfgasfgasfg fdgadfgafg fg

标题等于= Testing test1 test2 test3 test4 test5 test6 sdfgasfgasfg fdgadfgafg fg

出于某种原因,它抓住下一行的第一个单词aswel。

有没有人对如何解决此问题有任何建议?

3 个答案:

答案 0 :(得分:1)

试试这个:

function first4words($s) {
    return preg_replace('/((\w+\W*){4}(\w+))(.*)/', '${1}', $s);    
}

https://stackoverflow.com/a/965343/2701758

答案 1 :(得分:1)

可能有点hacky但我会尝试使用str_replace()来摆脱任何换行符。

$titleStripped = str_replace('\n', ' ', $title);
$pieces - explode(' ', $title);

取决于您的申请和预期数据。如果您期望的不仅仅是换行符,请使用preg_replace。无论哪种方式,都要在爆炸前准备好数据。

答案 2 :(得分:0)

试试这个(未经测试的代码):

//--- remove linefeeds
$titleStripped = str_replace('\n', ' ', $title);
//--- strip out multiple space caused by above line
preg_replace('/ {2,}/g',$titleStripped );
//--- make it an array
$pieces = explode( ' ', $titleStripped );
//--- get the first 4 words
$first_part = implode(" ", array_splice($pieces, 0, 4));