Analysis of Implementation Principle of JS PHP String Interception Function

  • 2021-08-09 06:45:13
  • OfStack

There are three js: slice () substring () substr ()

substr (start, length) is generally used. The first parameter is that the subscript of the starting position must be negative, subscript-1 refers to the last character in the string, subscript-2 refers to the penultimate character, and so on; The second parameter is the length of the substring to be truncated optionally, and the truncation direction is from left to right and will not change.

The truncated substring contains the starting position itself

PS: All indexes of strings start from 0

Spaces are all characters

substring (from, until) slice (from, until) are truncated from one index to another. They are different only when the parameter is negative. One point to emphasize: The substring does not include the element of the index value "until"

substring (0) slice (0) slice () is an interception of the entire string, meaningless

from required for substring

php:

1. substr (source string, starting position, [length])-Truncated string returns partial string

< ?php
$str ="phpddt.com";
echo substr($str,2);//pddt.com
echo substr($str,2,3);//pdd
echo substr ($str,-2); //om negative numbers are taken from the end
? >

But when you intercept Chinese strings, it is easy to have garbled characters, because a Chinese character is two bytes, while an English letter is one byte. The solution is as follows:

2. mb_substr (), used in the same way as substr

However, if you want to open the extension=php_mbstring. dll extension in php. ini, don't worry, all space quotients will open this extension.

< ?php
echo mb_substr ("php Point-to-Point", 1, 3, "UTF-8"); //hp point
? >

The code is as follows:

substr(string,start,length)

Where the parameters of start Positive number-starts at the specified position of the string Negative number-starting at the specified position from the end of the string 0-Begins at the first character in the string

Related articles: