【问题标题】:How can I truncate a string in php without cutting off words?如何在不截断单词的情况下截断 php 中的字符串?
【发布时间】:2013-07-06 22:11:25
【问题描述】:

我正在寻找以下案例的解决方案。 我有一个字符串

"This is a long string of words"

我只想使用前几个单词,但如果我只删除第 20 个字符之后的所有内容,它将如下所示:

"This is a long strin"

我可以抓住前三个字

implode(' ', array_slice(explode(' ', "This is a long string of words"), 0, 3));

但在某些情况下,三个单词“I I I”会太短。

如何在第 20 个字符之前获取尽可能多的单词?

【问题讨论】:

  • 您使用什么语言? C++、Java、C#、Php?
  • 哦,我没提,php
  • 可以使用正则表达式,也可以搜索单词之间的空格,使用split命令生成单词数组。
  • 试试这个链接,可能对你有帮助...stackoverflow.com/a/26098951/3944217

标签: php string


【解决方案1】:

echo array_shift(explode("\n", wordwrap($text, 20)));

文档:

【讨论】:

  • 添加了一些文档链接。 +1 使用我忘记的功能 XD
【解决方案2】:

在我用 PHP 给你答案之前,你有没有考虑过下面的 CSS 解决方案?

overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;

这将导致文本在最合适的位置被截断,并用省略号 ... 标记截断。

如果这不是你想要的效果,试试这个 PHP:

$words = explode(" ",$input);
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎
// then just cut that word off at 20 characters
if( strlen($words[0]) > 20) $output = substr($words[0],0,20);
else {
    $output = array_shift($words);
    while(strlen($output." ".$words[0]) <= 20) {
        $output .= " ".array_shift($words);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-04
    • 2019-01-03
    • 2021-10-28
    • 2011-10-02
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多