I'm want to convert string to array

$str = "[cat=[0=php,script=[js]],id=4,foo=bar]";

how to write preg pattern for change $str to :

$str = "[cat=[0=php,script=[js]]_-_id=4_-_foo=bar]";

If convert , to _-_

I can convert this string to array by foreach, but i can't convert , to _-_ in this string

I'm want convert only ,id=4,foo=bar to _-_id=4_-_foo=bar, No convert [0=php,script=[js]] to [0=php_-_script=[js]]

have any idea?

Recommended Answers

All 5 Replies

It is very hard to make that distinction. Is this a rule you can logically describe?

how to by foreach cycle

convert any level string :

 $str = "[cat=[0=php,script=[js]],id=4,foo=bar,....]";

to :

$str = "[cat=[0=php,script=[js]]_-_id=4_-_foo=bar_-_ ...]";

have any idea?

How about this:

    $str = "[cat=[0=php,script=[js]],id=4,foo=bar]";
    $arr = explode(',' , $str); 
    $arr[2] = "_-_".$arr[2];
    $arr[3] = "_-_".$arr[3];
    $str = implode('', $arr);
Member Avatar

Quick 'n' dirty. Assuming that you only want to replace 'top level' commas:

$str = '[cat=[0=php,script=[js]],id=4,foo=bar,....]';
$char = str_split($str);

$newstring = '';
foreach($char as $s)
    if($s == '[')$level++;
    if($s == ']')$level--;
    if($s == ',' && $level == 1)$s = '_-_';
    $newstring .= $s;
echo $newstring;
Member Avatar

Whatever it is you are trying to do... It looks like a recipe for a disaster.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.