English string intercept function in PHP

Source: Internet
Author: User
Tags php tutorial
1/**
2 * PHP Tutorial get string in english mix length
3 * @param $str string
4 * @param $ $charset string encoding
5 * @return return length, 1 Chinese = 1 bits, 2 english = 1 bits
6 */
7 function Strlength ($str, $charset = ' utf-8 ') {
8 if ($charset = = ' Utf-8 ') $str = Iconv (' utf-8 ', ' gb2312 ', $str);
9 $num = strlen ($STR);
$cnnum = 0;
for ($i =0; $i < $num; $i + +) {
if (Ord (substr ($str, $i +1,1)) >127) {
$cnnum + +;
$i + +;
15}
16}
$ennum = $num-($cnnum *2);
$number = ($ennum/2) + $cnnum;
return Ceil ($number);
20}
21st
22//test output length is 15
$str 1 = ' test test and test testing test ';
$str 2 = ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ';
$str 3 = ' AA Test AA Test AA test aaaaaa ';
Echo Strlength ($str 1, ' gb2312 ');
Echo Strlength ($str 2, ' gb2312 ');
Echo Strlength ($str 3, ' gb2312 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.