Inorder to split the string i have used the following code.
$string = "-sev*yes-sev1*no-sev2*yes";
split('[-*]', $string).
As split is deprecated, can you please suggest an alternative to split the string into an array. I have tr开发者_JS百科ied with explode, but it is not serving my purpose. The output should look like,
Array
(
[0] => sev
[1] => yes
[2] => sev1
[3] => no
[4] => sev2
[5] => yes
)
Thank u all for ur responses..I tried preg_split('[-*]', $string)
. It has split has the string character wise. I have modified it to preg_split('/[-*]/', $string)
. It is working well. It would be great if you can explain me the difference.
You can use preg_split as:
$string = "-sev*yes-sev1*no-sev2*yes";
$array = preg_split('/-|\*/', $string,-1, PREG_SPLIT_NO_EMPTY);
or
$array = preg_split('/-|\*/', $string);
alternatively you can also use strtok:
$tok = strtok($string, "-*");
$array = array();
while ($tok !== false) {
$array[] = $tok;
$tok = strtok("-*");
}
EDIT:
In
preg_split('[-*]', $string);
the [ ]
are treated as delimiters and not as char class hence you are using the regex -*
for splitting which means zero or more hyphens.
but in
preg_split('/[-*]/', $string);
you are using the regex [-*]
which is the char class to match either *
or a -
you can use explode or preg_split.
Preg_split is what you're looking for.
Just change split to preg_split.
preg_split() in PHP Manual
There are mainly two replacements for split:
- If you need to use regular expressions, use
preg_split()
. - If you do not need to use regular expressions, use
explode()
, as it is faster thanpreg_split()
Well, assuming your expected output is array('sev', 'yes', 'sev1', 'no', 'sev2', 'yes')
, you can use preg_split
:
$data = preg_split('/[-*]/', $string, -1, PREG_SPLIT_NO_EMPTY);
Or, considering that it looks like you have keyed segments (meaning that the first yes
is bound to sev
, the first no
is bound to sev1
, etc), you might be better off doing either multiple explodes:
$result = array();
$data = explode('-', $string);
foreach ($data as $str) {
if (empty($str)) continue;
list ($key, $value) = explode('*', $str);
$result[$key] = $value;
}
Or converting it to a url style segment, and using parse_str
...
$tmp = str_replace(array('-', '*'), array('&', '='), $string);
parse_str($tmp, $result);
Both of these will generate arrays like:
array(
'sev' => 'yes',
'sev1' => 'no',
'sev2' => 'yes',
);
Use preg_split()
.
$string = "-sev*yes-sev1*no-sev2*yes";
$result = preg_split('/[-*]/', $string);
精彩评论