Splitting string into array with delimiters
Hello my programmers friends, how are you all? Hope all are doing well and are fine too. I am again here with some sort of head ace. I mean I have a small doubt for which I am seeking your help. So please me. The thing is that I want to chop the text using two or more delimiters and store it in the array format. I have completely no idea what to do as I am new in the programming field. So please help me put and thank you to all in advance
Re: Splitting string into array with delimiters
You can use a preg_split() function, this will help you in splitting up the string. It splits up the string using a regular expression match which is for the delimiters. The explode() function can also be used for splitting up the string in to substrings but it can use only the simple string as the delimiter. But I would say that explode() is fast enough than regular expression, but you should still around to the preg_split() for the better understanding.
Re: Splitting string into array with delimiters
Yes go for preg_split.
Syntax for it : array preg_split (string pattern, string subject [, int limit [, int flags]])
Note: if you specify the limit, the4n returned substring will be only up to the limit but if you specify -1 then there exists no limits. You also need to set a flag for the splitting. If you set PREG_SPLIT_NO_EMPTY as a flag then the returned string would contain non-empty pieces and if you set PREG_SPLIT_DELIM_CAPTURE as a flag then parenthesized expression in the delimiter pattern will be arrested and revisited along with it.
Re: Splitting string into array with delimiters
Example: This example will split up the main string into the words.
$string = 'Split this string as an example.';
$words = preg_split('@[\W]+@', $string)
print_r($words);
Output:
[0] => Split
[1] => this
[2] => string
[3] => as
[4] => an
[5] => example.
Re: Splitting string into array with delimiters
Here you will find the example using the limits
$str = 'Hello! Your problem is solved';
$ans = preg_split('@[\W]+@', $str, 2);
print_r($ans);
Output is:
[0] => Hello!
[1] => Your problem is solved
Re: Splitting string into array with delimiters
I think using explode will be much easier for you as it is much simpler than the other one. Take my opinion and use explode().The specialty of explode is to break up the string into the array.
Syntax:
explode(separator,string,limit)
separator: her you can specify where the string must be broken.
String: This is the string which is to be splited.
Limit: This will specify the number of array elements to be returned.
Re: Splitting string into array with delimiters
Here is the small example for the same i.e explode().
<?php
$str = "Using explode is easy.";
print_r (explode(" ",$str));
?>
Output:
Array
(
[0] => Using
[1] => explode.
[2] => is
[3] => easy.
)