我有一个用PHP编写的代码片段,它从数据库中提取一个文本块,并将其发送到网页上的一个小部件。原文可以是一篇很长的文章,也可以是一两个短句;但是对于这个小部件,我不能显示超过200个字符。我可以使用substr()在200个字符处切断文本,但结果将在单词中间切断——我真正想要的是在200个字符前的最后一个单词的末尾切断文本。


当前回答

我以前用过这个

<?php
    $your_desired_width = 200;
    $string = $var->content;
    if (strlen($string) > $your_desired_width) {
        $string = wordwrap($string, $your_desired_width);
        $string = substr($string, 0, strpos($string, "\n")) . " More...";
    }
    echo $string;
?>

其他回答

我将使用preg_match函数来做到这一点,因为您想要的是一个相当简单的表达式。

$matches = array();
$result = preg_match("/^(.{1,199})[\s]/i", $text, $matches);

表达式的意思是“匹配从长度1-200开始以空格结尾的任何子字符串”。结果在$result中,匹配在$matches中。这就解决了你最初的问题,即以任意空格结束的问题。如果你想让它以换行符结束,将正则表达式更改为:

$result = preg_match("/^(.{1,199})[\n]/i", $text, $matches);
$shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);

描述:

^ -从字符串开头开始 ([\s\ s]{1200}) -从1到200的任意字符 [\ s] + ?-在短文本结尾不包含空格,这样我们就可以避免使用word…而不是word… [\s\ s]+ -匹配所有其他内容

测试:

让我们加上一些其他的r Regex101.com orrrr正好200个字符。 Regex101.com后第五r orrrrr排除。

享受。

使用strpos和substr:

<?php

$longString = "I have a code snippet written in PHP that pulls a block of text.";
$truncated = substr($longString,0,strpos($longString,' ',30));

echo $truncated;

这将为您提供一个在30个字符后的第一个空格处截断的字符串。

当我注意到wordwrap函数的$break参数时,产生了以下解决方案:

字符串$str [, int $width = 75[,字符串$break = "\n" [, bool $cut = false]])

下面是解决方案:

/**
 * Truncates the given string at the specified length.
 *
 * @param string $str The input string.
 * @param int $width The number of chars at which the string will be truncated.
 * @return string
 */
function truncate($str, $width) {
    return strtok(wordwrap($str, $width, "...\n"), "\n");
}

示例# 1。

print truncate("This is very long string with many chars.", 25);

上面的例子将输出:

This is very long string...

例# 2。

print truncate("This is short string.", 25);

上面的例子将输出:

This is short string.

这是一个小修复mattmac的答案:

preg_replace('/\s+?(\S+)?$/', '', substr($string . ' ', 0, 201));

唯一的区别是在$string的末尾添加一个空格。这确保了最后一个词不会像ReX357的注释那样被切断。

我没有足够的代表点添加这作为一个评论。