views:

82

answers:

7

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 tried 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.

+3  A: 

Preg_split is what you're looking for.

Simon
+1  A: 

Just change split to preg_split.

preg_split() in PHP Manual

killer_PL
+3  A: 

you can use explode or preg_split.

Petr Kozelek
upvoted for suggesting 2 alternatives :-)
Chris
Is explode an alternative here? He needs regex to use '[-*]', eplode does not handle regexp.
Marco Demajo
+4  A: 

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 -

codaddict
+1  A: 

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 than preg_split()
Frxstrem
+1  A: 

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',
);
ircmaxell
A: 

Use 'preg_split'.

$string = "-sev*yes-sev1*no-sev2*yes"; 
$result = preg_split('/[-*]/', $string);
Marco Demajo