我有一个用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的注释那样被切断。
我没有足够的代表点添加这作为一个评论。
推荐文章
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- Ruby数组到字符串的转换
- 为什么在Java和。net中不能修改字符串?
- 如何要求一个分叉与作曲家?
- 如何创建一个日期对象从字符串在javascript
- 在Android上将字符串转换为整数
- 删除字符串的最后3个字符
- 如何在php中创建可选参数?
- 如何大写一个字符串的第一个字母在省道?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?