In the project, encountered a demand, such as I want to intercept a string of strings, and do not want to intercept half of the word, read the PHP Manual of this mb_strimwidth () function, is said to not break the word, but the test did not succeed, so I wrote a first, although some small problems, but barely able to use, Have time to encapsulate the better. The principle of this function is to use WordWrap () to break the word and then use Mb_strlen () to calculate the length of the word and intercept 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);
Results:
ReadOnly This Boolean attribute indicates, the user cannot modify value of control. Unlike disabled attribute, ...
/**
* This function intercepts the English string, does not interrupt the English word, that is, does not cut a word half
* Note: Not available in Chinese, but can also be changed
* Note: At present, the function is a bit small bug, $cutlength not refer to the length, but to calculate the length of all words to stop when the number, 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{
Calculates the total length of the current word
$totalLength = 0;
$datas = $newwords = Array ();
Scrambled 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 the word
$totalLength + = $length;
If the length is less than the Intercept, save
if ($totalLength < $cutlength) {
Array_push ($newwords, $word);
}else{
Break
}
}
Generate a new string
$str = Trim (Implode ("", $newwords));
return empty ($STR)? $STR: $str. ". $replace;
}
}
This article source: http://www.52blogger.com/archives/819
http://www.bkjia.com/PHPjc/363855.html www.bkjia.com true http://www.bkjia.com/PHPjc/363855.html techarticle in the project, encountered a demand, such as I want to intercept a string of strings, and do not want to intercept half of the word, read the PHP Manual of this mb_strimwidth () function, is said to not break the word, but ...