如何截断句子或单词末尾的字符串

时间:2011-02-01 14:55:44

标签: php

我想使用博客文章的一部分作为帖子的介绍,然后在最后添加“阅读更多”链接,但我找不到一种方法来在文本末尾对文本进行舍入。单词或句子。下面的代码会遇到一个空的无限循环。

<?php

$num_of_words = 400;
while (! substr($article, $num_of_words, 1) != "")
     $num_of_words++;

?>

请帮忙吗? 感谢

4 个答案:

答案 0 :(得分:1)

另一种方法是:

if (strlen($article) <= 400)
    $intro = $article;
else
    $intro = substr($article, 0, strrpos($article, ' ', strlen($article)-400));

答案 1 :(得分:0)

你可以使用正则表达式,如果你想得到前25个单词,你可以使用像

这样的东西

^([\w,\.:;]+\s+){1,25}

如果您需要有关正则表达式的更多帮助,请询问......

答案 2 :(得分:0)

<?php

$num_of_words = 400;

$art=explode(' ',$article);
$shortened='';
for ($i=0 ; $i<=$num_of_words ; $i++){
    $shortened.=$art[$i].' ';
}
echo $shortened;
?>

这将打印出前400个词......

答案 3 :(得分:0)

假设有一个最大长度你不想超过,即使没有空格,这样的东西也会起作用:

$maxlength=100; //100 characters
$mystring='I want to use part of a blog post as the introduction to the post and then add a "read more" link at the end, but I couldn't find a way to round up the text either at the end of a word or sentence. The code below runs into an empty infinite loop.';

$mystring=substr($mystring,0,$maxlength); //now string can't be too long
$last_space=strrpos($mystring,' ');
$mystring=substr($mystring,-,$last_space);

但是如果你真的希望通过字数计算,那么请记住单词可能很长,这样的正则表达式应该匹配前25个单词。

/^(\w+\b){1,25}/
相关问题