To separate strings, just use "str_split". The advantage is that even spaces will be used as elements of the array. My previous example was because the first string contained 2 spaces, while the latter one only had one. But the display you see when outputting is the same. You can also split according to other delimiters, such as "explode" or "preg_split",
To separate strings, just use "str_split". The advantage is that even spaces will be used as elements of the array. My previous example was because the first string contained 2 spaces, while the latter one only had one. But the display you see when outputting is the same.
You can also split according to other delimiters, such as "explode" or "preg_split",
PHP tutorial explode() function
php string function
Definition and Usage
The explode() function splits a string into an array.
Grammar
explode(separator,string,limit) parameter description
separator required. Specifies where to split the string.
string required. The string to split.
limit is optional. Specifies the maximum number of array elements returned.
Example
In this example, we will split the string into an array:
$str = "hello world. it's a beautiful day.";
print_r (explode(" ",$str));
?>
Output:
array
(
[0] => hello
[1] => world.
[2] => it's
[3] => a
[4] => beautiful
[5] => day.
)
str_split split function
Definition and usage
The str_split() function splits a string into an array.
Grammar
str_split(string,length) parameter description
string required. Specifies the string to be split.
length is optional. Specifies the length of each array element. The default is 1.
Description
If length is less than 1, the str_split() function returns false.
If length is greater than the length of the string, the entire string will be returned as the only element of the array.
Example
Example 1
print_r(str_split("hello"));
?>
Output:
array
(
[0] => h
[1] => e
[2] => l
[3] => l
[4] => o
)
Example 2
print_r(str_split("hello",3));
?>
Output:
array
(
[0] => hel
[1]
preg_split -- Split string using regular expression
Description
array preg_split (string pattern, string subject [, int limit [, int flags]])
Returns an array containing the substrings in subject split along boundaries that match pattern.
If limit is specified, at most limit substrings will be returned. If limit is -1, it means there is no limit and can be used to continue specifying optional parameter flags.
flags can be any combination of the following flags (combined with the bitwise OR operator |):
preg_split_no_empty
If this flag is set, preg_split() only returns non-empty components.