0

i have string like this

$string = '$foo$wow$123$$$ok$';

i want to return empty string and save string in array like this

0 = foo
1 = wow
2 = 123
3 = 
4 =
5 = ok

i use PREG_SPLIT_NO_EMPTY, i know when make PREG_SPLIT_NO_EMPTY return is not empty, but i want any result empty, i want my result save in variable array like in PREG_SPLIT_NO_EMPTY with $chars[$i];

this is my preg_split :

$chars = preg_split('/[\s]*[$][\s]*/', $string, -1, PREG_SPLIT_NO_EMPTY); 

for($i=0;$i<=5;$i++){
     echo $i.' = '.$chars[$i];
}

i want, my result show with looping. no in object loop i want pure this looping:

for($i=0;$i<=5;$i++){
     echo $i.' = '.$chars[$i];
}

to show my result.

how i use this preg_split, thanks for advance...

pwcahyo
  • 67
  • 1
  • 10

2 Answers2

3

use explode

$str = '$foo$wow$123$$$ok$';
$res = explode ("$",$str);

print_r($res);


Array
(
    [0] => 
    [1] => foo
    [2] => wow
    [3] => 123
    [4] => 
    [5] => 
    [6] => ok
    [7] => 
)
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

Using explode adds the empty entrys to the front and the back.

This one matches the tc's expected output:

$str = '$foo$wow$123$$$ok$';
preg_match_all("@(?<=\\$)[^\$]*(?=\\$)@", $str, $res);

echo "<pre>";
print_r($res);
echo "</pre>";

[0] => Array
    (
        [0] => foo
        [1] => wow
        [2] => 123
        [3] => 
        [4] => 
        [5] => ok
    )
dognose
  • 20,360
  • 9
  • 61
  • 107