PHP string intercept function usage detailed

Source: Internet
Author: User

The

substr () is a function of a truncated string that PHP can only handle in English, numbers, but not the Chinese mix, so if you need to intercept the Chinese mixed string, you can refer to the second code.

  code is as follows copy code

//construction string
  $STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  echo "original string:". $str. "
";
 //interception in various ways
  $STR 1 = substr ($STR, 5);
  echo "begins with the 5th character to the last:". $str 1. "
";
  $STR 2 = substr ($str, 9,4);
  Echo takes 4 characters starting from the 9th character: ". $str 2."
";
  $STR 3 = substr ($str,-5);
  Echo takes the penultimate 5 characters: ". $str 3."
";
  $STR 4 = substr ($str, -8,4);
  Echo takes 4 characters backwards from the penultimate character: ". $str 4."
";
  $STR 5 = substr ($str, -8,-2);
  Echo begins with the last 8th character until the penultimate character: ". $str 5."
";
Run code to copy code save code


 

/*
------------------------------------------------------
Parameters:
$str _cut A string that needs to be truncated
$length maximum length allowed for string display

Program function: Intercept all corners and half-width (Chinese and English) mixed strings to avoid garbled
------------------------------------------------------
*/

  code is as follows copy code
function Substr_cut ($str _cut, $length)
{
    if (strlen ($str _cut) > $length)
    {
        for ($i =0; $i < $length; $i + +)
         if (Ord ($str _cut[$i]) > 128)     $i + +;
        $str _cut = substr ($str _cut,0, $i). ".";
   }
    return $str _cut;
}

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.