确保PHP substr在单词而不是字符上完成 [英] Making sure PHP substr finishes on a word not a character

查看:63
本文介绍了确保PHP substr在单词而不是字符上完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用substr函数,但这会很高兴在一个单词的中途结束一个字符串.我希望字符串在单词的结尾处结束,我将如何去做呢?它会涉及正则表达式吗?任何帮助,非常感谢.

I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.

这是我到目前为止所拥有的.只是SubStr ...

This is what I have so far. Just the SubStr...

echo substr("$body",0,260);

欢呼

推荐答案

可以使用正则表达式来完成,类似这样的操作将从字符串开头到单词边界最多包含260个字符:

It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:

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

或者,您可以使用 wordwrap 函数将$ body分成几行,然后仅提取第一个线.

Alternatively, you could maybe use the wordwrap function to break your $body into lines, then just extract the first line.

这篇关于确保PHP substr在单词而不是字符上完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆