mai*_*oui 105 php string strlen
我的MySQL数据库中有一个描述字段,我在两个不同的页面上访问数据库,一个页面显示整个字段,但另一方面,我只想显示前50个字符.如果说明字段中的字符串少于50个字符,那么它将不会显示...,但如果不是,我将在前50个字符后显示....
示例(完整字符串):
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 ...
Run Code Online (Sandbox Code Playgroud)
例2(前50个字符):
Hello, this is the first example, where I am going ...
Run Code Online (Sandbox Code Playgroud)
Nie*_*sol 290
PHP的方法很简单:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
Run Code Online (Sandbox Code Playgroud)
但是你可以用这个CSS实现更好的效果:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)
现在,假设元素具有固定的宽度,浏览器将自动中断并...为您添加.
jim*_*rin 166
您也可以通过这种方式实现所需的修剪:
mb_strimwidth("Hello World", 0, 10, "...");
Run Code Online (Sandbox Code Playgroud)
哪里:
Hello World:要修剪的字符串.0:字符串开头的字符数.10:修剪过的字符串的长度....:修剪后的字符串末尾添加的字符串.这将返回Hello W....
请注意,10是截断字符串的长度+添加的字符串!
文档:http://php.net/manual/en/function.mb-strimwidth.php
nic*_*ckb 36
使用wordwrap()截断字串不打破的话如果字符串超过50个字符,并且只需添加...在最后:
$str = $input;
if( strlen( $input) > 50) {
$str = explode( "\n", wordwrap( $input, 50));
$str = $str[0] . '...';
}
echo $str;
Run Code Online (Sandbox Code Playgroud)
否则,使用substr( $input, 0, 50);会破坏单词的解决方案.
Tch*_*upi 12
if (strlen($string) <=50) {
echo $string;
} else {
echo substr($string, 0, 50) . '...';
}
Run Code Online (Sandbox Code Playgroud)
<?php
function truncate($string, $length, $stopanywhere=false) {
//truncates a string to a certain char length, stopping on a word if not specified otherwise.
if (strlen($string) > $length) {
//limit hit!
$string = substr($string,0,($length -3));
if ($stopanywhere) {
//stop anywhere
$string .= '...';
} else{
//stop on a word.
$string = substr($string,0,strrpos($string,' ')).'...';
}
}
return $string;
}
?>
Run Code Online (Sandbox Code Playgroud)
我多次使用上面的代码片段..
| 归档时间: |
|
| 查看次数: |
119469 次 |
| 最近记录: |