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


当前回答

你可以试试这个

substr( $str, 0, strpos($str, ' ', 200) ); 

其他回答

给你:

function neat_trim($str, $n, $delim='…') {
   $len = strlen($str);
   if ($len > $n) {
       preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
       return rtrim($matches[1]) . $delim;
   }
   else {
       return $str;
   }
}

当我注意到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.

用这个:

下面的代码将删除','。如果你有任何其他字符或子字符串,你可以用它来代替','

substr($string, 0, strrpos(substr($string, 0, $comparingLength), ','))

//如果你有另一个字符串帐户

substr($string, 0, strrpos(substr($string, 0, $comparingLength-strlen($currentString)), ','))
$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排除。

享受。

我将使用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);