在不拆分单词的情况下限制 Php 中标题的字符数 [英] Limiting the Character Count of the Title in Php without splitting words

查看:47
本文介绍了在不拆分单词的情况下限制 Php 中标题的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
PHP 中的缩短字符串(仅限完整单词)
如何从字符串中获取前 x 个字符,而不切断最后一个单词?

很像这个问题:How使用 PHP 限制标题标签的长度

...答案类似于:

 [title]  ?php echo substr( $mytitle, 0, 70 );  [/title]

...但是有没有什么办法可以在解决方案不会将任何单词减半的情况下实现这一点?那么如果单词部分超过限制的字符数,解决方案将删除整个单词,而不是将其限制在字符数?

...but is there any way to accomplish this where the solution does not cut any words in half? So if the word partially exceeds the character count of the limit, the solution would remove the full word, rather than limit it at the character count?

推荐答案

这可能会让你达到 95%,但它并不完美......

This might get you 95% there, but it's not perfect...

$mytitle = 'How to Limit the Length of the Title Tag using PHP';
$arr = explode(' ',$mytitle);
$string = '';

foreach($arr as $word) {
    if(strlen($string) > 69) break;
    $string .= ' ' . $word;
}

echo $string;

这篇关于在不拆分单词的情况下限制 Php 中标题的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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