In the project, you encounter a requirement, if I want to intercept a string of words, but do not want to intercept half of the word, read the PHP Manual of this mb_strimwidth () function, it is said to not interrupt the word, but the test did not succeed, and then write their own first, although some small problems, but can barely use, Have time to encapsulate the better. The principle of this function is to use WordWrap () to interrupt the word, and then use Mb_strlen () to calculate the length of the word, interception to the need to be intercepted length. Test as follows:
Original string
$str = ' ReadOnly This boolean 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" Control. Long GE Blog's The value of a read-only control are still submitted with the form.
Echo wordcut ($STR, 100);
Results:
ReadOnly This boolean indicates the user cannot modify value of control. Unlike disabled attribute, ...
/**
* This function intercepts English strings and does not interrupt English words, which means that one word is not intercepted in half
* Note: Does not apply to Chinese, of course, change can also
* Note: This function is a little bug, $cutlength not the length, but the length of all words to the number of stops, in fact, the length of the space is ignored
*/
function Wordcut ($string, $cutlength =, $replace = ' ... ') {
Insufficient length to return directly
if (Mb_strlen ($string) <= $cutlength) {
return $string;
}else{
Calculate the total length of the current word
$totalLength = 0;
$datas = $newwords = Array ();
Shuffle 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 if less than the length of the Intercept
if ($totalLength < $cutlength) {
Array_push ($newwords, $word);
}else{
Break
}
}
Generate a new string
$str = Trim (Implode ("", $newwords));
return empty ($STR)? $STR: $str. $replace;
}
}