Code
<? Php
/*
* 1. Split the string by the specified symbol and return the number of elements after the split. The method is very simple, that is, to check the number of separators in the string, and then add one, which is the required result.
* $ Str: string to be split
* $ Split: Separator
*/
Function Get_StrArrayLength ($ str, $ split)
{
$ Location = ''; // current location
$ Start = ''; // start position of the search
$ Length = 1; // record array length
$ Str = trim ($ str); // remove Spaces
$ Location = strpos ($ str, $ split );
While ($ location)
{
$ Start = $ location + 1;
$ Location = strpos ($ str, $ split, $ start );
$ Length = $ length + 1;
}
Return $ length;
}
/*
* 2. Split the string by the specified symbol. Return the nth element of the specified index after the split, which is as convenient as an array.
* $ Str: string to be split
* $ Split: Separator
* $ Index: number of elements
*/
Function Get_StrArrayStrOfIndex ($ str, $ split, $ index)
{
$ Location = 0; // current location
$ Start = 0; // start position of the search
$ Next = 1; // The next location
$ Seed = strlen ($ index); // seed (split String Length)
$ Str = trim ($ str); // remove Spaces
$ Location = strpos ($ str, $ split );
While ($ location! = False & $ index> $ next)
{
$ Start = $ location + $ seed;
$ Location = strpos ($ str, $ split, $ start );
$ Next = $ next + 1;
}
If ($ location = 0)
{
$ Location = strlen ($ str) + 1;
}
/*
* There are two cases: 1. The character string does not have a separator number. 2. The character string contains a separator number. After a while loop exists, $ location is 0, by default, there is a separator behind the string.
*/
Return substr ($ str, $ start, $ location-$ start );
}
/*
* 3. combine the two functions above to traverse the elements in the string like an array. Of course, store them directly in the array.
* $ Str: string to be split
* $ Split: Separator
*/
Function mySplit ($ str, $ split)
{
$ Next = 1;
$ Arr = array ();
While ($ next <= Get_StrArrayLength ($ str, $ split ))
{
Array_push ($ arr, Get_StrArrayStrOfIndex ($ str, $ split, $ next ));
$ Next = $ next + 1;
}
Return $ arr;
}
/*
* The test is as follows:
**/
$ STR = '2017 | 123 | 100 ';
$ Split = '| ';
$ Arr = mysplit ($ STR, $ split );
// Output array structure:
Print_r ($ ARR );
?>
Output result:
Array ([0] => 123 [1] => 456 [2] => 789)