Trong bài này mình sẽ hướng dẫn cách sử dụng hàm TRUNCATE
trong MySQL
thông qua cú pháp và ví dụ thực tế.
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.
1. Mô tả
Hàm TRUNCATE
trả về một số bị
cắt cụt đến một số vị trí thập phân nhất định.
2. Cú pháp
Cú pháp của hàm TRUNCATE
trong MySQL
là:
TRUNCATE[ number, decimal_places ]
Trong đó:
Bài viết này được đăng tại [free tuts .net]
number
: Số để cắt ngắndecimal_places
: Số lượng các vị trí thập phân cắt ngắn đến. Giá trị này phải là số nguyên dương hoặc âm.
3. Version
Hàm TRUNCATE
có thể được sử dụng trong các phiên bản sau của MySQL
:
- MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
4. Ví dụ
mysql> SELECT TRUNCATE[115.34523, 0]; Ket qua: 115 mysql> SELECT TRUNCATE[115.34523, 1]; Ket qua: 115.3 mysql> SELECT TRUNCATE[115.34523, 2]; Ket qua: 115.34 mysql> SELECT TRUNCATE[115.34523, -1]; Ket qua: 110 mysql> SELECT TRUNCATE[115.34523, -2]; Ket qua: 100 mysql> SELECT TRUNCATE[-115.34523, 0]; Ket qua: -115
Im looking for a soluting for the followting case. I have a string
"This is a long string of words"
I want to use only the first few words, but if I just cut everything after 20th character, it will look like this:
"This is a long strin"
I can grab first 3 words
implode[' ', array_slice[explode[' ', "This is a long string of words"], 0, 3]];
But in some cases, 3 words are going to be too short "I I I".
How can I grab as many words as possible before 20th character?
Rob
12.5k4 gold badges36 silver badges54 bronze badges
asked Jul 6, 2013 at 22:11
4
echo array_shift[explode["\n", wordwrap[$text, 20]]];
Documentation:
array_shift
explode
wordwrap
answered Jul 6, 2013 at 22:23
RobRob
12.5k4 gold badges36 silver badges54 bronze badges
1
Before I give you an answer in PHP, have you considered the following CSS solution?
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
This will
result in the text being cut off at the most appropriate place and an ellipsis ...
marking the cut-off.
If this is not the effect you're looking for, try this PHP:
$words = explode[" ",$input];
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia
// then just cut that word off at 20 characters
if[ strlen[$words[0]] > 20] $output = substr[$words[0],0,20];
else {
$output = array_shift[$words];
while[strlen[$output." ".$words[0]]