如果字符串太长,则添加... PHP [英] Add ... if string is too long PHP

查看:85
本文介绍了如果字符串太长,则添加... PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MySQL数据库中有一个description字段,我在两个不同的页面上访问数据库,一个页面显示整个字段,但在另一个页面上,我只想显示前50个字符.如果description字段中的字符串少于50个字符,则不会显示...,但是如果不是,我将在前50个字符后显示....

I have a description field in my MySQL database, and I access the database on two different pages, one page I display the whole field, but on the other, I just want to display the first 50 characters. If the string in the description field is less than 50 characters, then it won't show ... , but if it isn't, I will show ... after the first 50 characters.

示例(完整字符串):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

示例2(前50个字符):

Exmaple 2 (first 50 characters):

Hello, this is the first example, where I am going ...

推荐答案

PHP的实现方法很简单:

The PHP way of doing this is simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

但是您可以使用以下CSS达到更好的效果:

But you can achieve a much nicer effect with this CSS:

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

现在,假设元素的宽度固定,浏览器将自动断开并为您添加....

Now, assuming the element has a fixed width, the browser will automatically break off and add the ... for you.

这篇关于如果字符串太长,则添加... PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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