PHP real time statistics of Chinese words and differences
- 2021-11-29 06:10:51
- OfStack
1. How to count the number of Chinese words correctly in PHP? This is a problem that has puzzled me for a long time. There are many functions in PHP that can calculate the length of strings. For example, in the following example, three functions, strlen, mb_strlen and mb_strwidth, are used to test the length of statistical strings and see if Chinese is calculated into several bytes:
echo strlen(" How do you do ABC") . "";
# Output 9
echo mb_strlen(" How do you do ABC", 'UTF-8') . "";
# Output 5
echo mb_strwidth(" How do you do ABC") . "";
# Output 7
From the above test, we can see that strlen counts Chinese characters as 3 bytes, while mb_strlen doesn't care
< /script > Both Chinese and English count as 1 byte, while mb_strwidth counts Chinese as 2 bytes, so mb_strwidth is what we want: 2 bytes in Chinese and 1 byte in English.
It is also recommended to use mb_strimwidth for intercepting strings, which is also calculated according to the mode of 2 bytes in Chinese and 1 byte in English. If the number of words exceeds the intercepting requirements, this function can also automatically add '…' at the back.
mb_strimwidth($post_excerpt,0,240,'...','utf-8');
Note that adding 'utf-8' encoding parameter at last can avoid the problem of garbled Chinese interception.
2.
<script type="text/javascript">
var len = $('#Form-field-Course-description').text().length;
$('#Form-field-Course-description-group').append('<div id="txtNum" style="position: absolute;right: -50px;bottom: 18px;"></div>');
var len=$('#Form-field-Course-description').val().length;
$('#txtNum').text(len+"/500");
$('#Form-field-Course-description').bind('input propertychange', function() {
var val=$(this).val();
var len=val.length;
if(len>500){
len=500;
$(this).val(val.substring(0,500));
}
$('#txtNum').text(len+"/500");
});
</script>
The length of textarea is obtained according to the background update of Octobercms, and events are monitored through input and propertychange events
Summarize