SoFunction
Updated on 2025-03-02

PHP real-time statistics on the number of Chinese characters and differences

1. How to correctly count the number of Chinese characters in PHP? This is a problem that has troubled me for a long time. There are many functions in PHP that can calculate the length of a string. For example, in the following example, we use strlen, mb_strlen, and mb_strwidth respectively to test the length of the string and see how many bytes of Chinese are counted:

echo strlen("Hello ABC") . "";
# Output 9echo mb_strlen("Hello ABC", 'UTF-8') . "";
# Output 5echo mb_strwidth("Hello ABC") . "";
#Output 7

From the above test, we can see that strlen counts Chinese characters into 3 bytes, mb_strlen doesn't care

</script> Whether Chinese or English is 1 byte, while mb_strwidth calculates 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 to intercept strings, which is calculated according to the 2 bytes in Chinese and 1 byte in English. If the number of words exceeds the intercept requirements, this function can also automatically add '...' at the end.

mb_strimwidth($post_excerpt,0,240,'...','utf-8');

Note that adding the 'utf-8' encoding parameter in the end can avoid the problem of garbled code interception in Chinese.

2、

<script type="text/javascript">
  var len = $('#Form-field-Course-description').text().length;
  $('#Form-field-Course-description-group').append('<div  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=;
     if(len>500){
      len=500;
      $(this).val((0,500));
     }
    $('#txtNum').text(len+"/500");
  });
</script>

Obtain the textarea length according to Octobercms background update, listen to the event through input and propertychange event

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links