所以基本上我硬了一个非常大的字符串,我只想保存它的前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
出于某种原因,它在下一行抓住了第一个单词。
有人对如何解决这个问题有什么建议吗?
发布于 2013-09-20 00:33:45
这可能有点麻烦,但我会尝试使用str_replace()来消除任何换行符。
$titleStripped = str_replace('\n', ' ', $title);
$pieces - explode(' ', $title);不过,这取决于您的应用程序和预期数据。如果您期望的不只是换行,请使用preg_replace。不管怎样,在爆炸前准备好数据。
发布于 2013-09-20 00:31:41
试试这个:
function first4words($s) {
return preg_replace('/((\w+\W*){4}(\w+))(.*)/', '${1}', $s);
}发布于 2013-09-20 00:59:32
试试这个(未经测试的代码):
//--- 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));https://stackoverflow.com/questions/18907078
复制相似问题