Php intercepts string functions. 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 it will not interrupt words, but in the project, there is a need, such as I want to intercept a string, but do not want to intercept half of the word, after reading the mb_strimwidth () function in the php manual, it is said that it will not interrupt the word, but the test is not successful. Therefore, you can write it first. although there are some minor problems, you can barely use it, it is better to package it with time. 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;
}
}
The lift () function is said to not interrupt words,...