In the Web-oriented application, the foreground and background communication is a very common format is the string, so in the communication, we inevitably need to do the string of the spelling.
In the JS code, when we pass a string to the background code, we need to cut the string in the background to get the data we need. Similarly, in the background code (which I use in PHP) we pass a string to the foreground JS code, we also need to cut the string to get the data we need.
So, take a look at how to cut strings in JavaScript and PHP!
In javascript:
In JS, the commonly used methods of cutting strings are: substr, substring and split method, these three methods have their own characteristics, according to their own needs to choose their own.
SUBSTR: Returns a string of the specified length starting at the specified position.
Syntax: String.substr (start,length)
The string represents the strings we need to cut, and start represents the beginning of the string, that is, the count from this position, and length indicates how long to cut.
Instance code:
1 <script type= "Text/javascript" >2 var str= "Hello world!" ; 3 var strsub=str.substr (3,2); 4 alert (strsub); 5 </script>
The above code execution will output: Lo
SUBSTRING: Returns a string in two specified positions.
Syntax: string.substring (start,end)
The string represents the strings we need to cut, start indicates where the string starts (including start), and end represents the ending position (not including end).
1 <script type= "Text/javascript" >2 var SS; 3 var s = "The rain in Spain falls mainly in the plain." 4 ss = s.substring (n, +); 5 Alert (ss); 6 </script>
The above code executes the result: Spain we can actually find a rule that the length of the returned string after the cut is the absolute value of the start and end difference.
Split: Cuts the string with the specified character, and the cut string is saved as an array.
Instance code:
<script type= "Text/javascript" > str= "2,2,3,5,6,6"; var New Array (); STRs=str.split (","); for (i=0;i<strs.length; i++ ) { document.write (Strs[i]+ "<br/>");
The above code specifies the output result:
2
2
3
5
6
6
You should understand that split is cut with the specified character.
The above is a string cut in JavaScript, so let's look at how the string is cut in the background code PHP.
PHP: Explode () function: Splitting a string with a specified character
Instance code:
1 <? PHP 2 $str = "Hello World". I Love shanghai! " ; 3 Var_dump (Explode("",$str)); 4 ?>
The above code will be cut with a space for the specified character. The result is printed as an array to display in the page.
The above is my more commonly used in JavaScript and PHP string segmentation function, do a small summary.
JavaScript and PHP Common syntax--cutting strings