In the project, I encountered a requirement, such as intercepting a string and not wanting to intercept a half word. I read the mb_strimwidth () function in the php manual, it is said that the words will not be interrupted, but the test is not successful, so you can write your own first, although some small problems, but barely use it, there is time to encapsulate it better. the implementation principle of this function is to use wordwrap () to interrupt a word, and then use mb_strlen () to calculate the word length and intercept it to the length to be intercepted. test as follows:
// Original string
$ Str = 'readonly this boolean attribute indicates that the user cannot modify the value of the control. unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. long ge blog \'s The value of a read-only control is still submitted with the form. ';
Echo wordcut ($ str 100 );
// Result:
Readonly this boolean attribute indicates that the user cannot modify value of control. Unlike disabled attribute ,...
/**
* This function intercepts an English string and does not interrupt an English word. That is, it does not intercept half of a word.
* Note: it is not applicable to Chinese characters. Of course, it can be changed.
* Note: at present, this function has a small bug. $ cutlength does not refer to the length. Instead, it is used to calculate the length of all words and stops when it reaches this number. In fact, the length of space is ignored.
*/
Function wordcut ($ string, $ cutlength = 250, $ replace = '... '){
// Return directly if the length is insufficient
If (mb_strlen ($ string) <= $ cutlength ){
Return $ string;
} Else {
// Calculate the total length of the current word
$ TotalLength = 0;
$ Datas = $ newwords = array ();
// Disrupt text
$ Wrap = wordwrap ($ string, 1, "\ t ");
// Make up an array
$ Wraps = explode ("\ t", $ wrap );
Foreach ($ wraps as $ tmp ){
// Calculate the length of each word
$ Datas [$ tmp] = mb_strlen ($ tmp );
}
Foreach ($ datas as $ word => $ length ){
// Save the total length of a word
$ TotalLength + = $ length;
// Save the value if it is smaller than the truncated length.
If ($ totalLength <$ cutlength ){
Array_push ($ newwords, $ word );
} Else {
Break;
}
}
// Generate a new string
$ Str = trim (implode ("", $ newwords ));
Return empty ($ str )? $ Str: $ str. ''. $ replace;
}
}