0

假设我们有一个字符串patterns also provide us a common vocabulary to describe solutions

我们substr()这个字符串,所以我们有patterns also provide us a common vocabulary to desc

如何将最后一个字符串剪切到patterns also provide us a common vocabulary to

我的方法是:

$text = mb_substr($new['text'], 0, 100);

if(mb_substr($text, -1) != ' ') {

    $text_expl = explode(' ', $text);

    $text = implode(' ', array_splice($text_expl, 0, -1)) . ' ...';

}

有更好的东西吗?

也许正则表达式或一些 PHP 内置函数可以做类似的事情?

4

2 回答 2

4

这会找到最后一个空白并获取子字符串

$text = mb_substr($new['text'], 0, 100);
$i = mb_strrpos($text, ' ');
if ($i !== false)
    $text = mb_substr($text, 0, $i);
于 2012-12-19T11:50:04.140 回答
2

我会用这个:

if (preg_match('/^.{1,26}\b/s', $str, $match))
{
    echo $line=$match[0];
}

这会以您想要的方式截断文本。此外,当您指定更多字符时,字符串中实际上有更多字符,它只会简单地将整个字符串返回给您。这也是想要的结果。

以下方法也有效,但当字符串中的字符少于您指定的字符时会出现错误。

// Needs more than 260 characters in $str
echo substr($str, 0, strpos($str, ' ', 260));

因此,既然您无论如何都需要将其包装在一个if语句中,以检查 的长度$str,我会选择第一个选项。

于 2012-12-19T11:50:51.357 回答