首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将PHP中的字符串截断到与一定数量字符最接近的单词?

如何将PHP中的字符串截断到与一定数量字符最接近的单词?
EN

Stack Overflow用户
提问于 2018-01-05 07:17:52
回答 2查看 0关注 0票数 0

I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last 在200个字符之前。

EN

回答 2

Stack Overflow用户

发布于 2018-01-05 15:31:40

通过使用wordwrap功能。可以将文本分成多行,

代码语言:javascript
复制
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
票数 0
EN

Stack Overflow用户

发布于 2018-01-05 16:51:43

这将返回单词的前200个字符:

代码语言:javascript
复制
preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100007117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档