Re: pasring complex string question

From: Date: Fri, 08 Apr 2005 04:39:53 +0000
Subject: Re: pasring complex string question
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-212617@lists.php.net to get a copy of this message
Eli wrote:
Webmaster wrote:
Hello, i have a string looking like this. ## /T (KEY1)/V (VALUE1)|| ## /T (KEY2)/V (VALUE2)|| ## /V (VALUE3)/T (KEY3)|| I know want to separete it in to keys and values and insert them into an array. Note that /T always shows that teh upcoming value in() is a Key and that /V always is a Value. And that the set can be flipped. Thank you very much for helping. Mirco Blitz
It seems you complex yourself too much.. ;) Try using regexp with the 'e' modifier: <?php $data="## /T (KEY1)/V (VALUE1)|| ## /T (KEY2)/V (VALUE2)|| ## /V (VALUE3)/T (KEY3)||"; $data_array=array(); preg_replace(
    array(
    "/\#\#\s*/T\s*\(([^\)]*)\)\s*\V\s*\(([^\)]*)\)\s*\|\|/e",
    "/\#\#\s*/V\s*\(([^\)]*)\)\s*\T\s*\(([^\)]*)\)\s*\|\|/e"
    ),
    array(
    "\$data_array['\\1']='\\2';",
    "\$data_array['\\2']='\\1';"
    ),
    $data
); print_r($data_array); //see if you get it as expected ?> I believe there's an easier way to store your data as strings (like serialize), so why not using them?! see alse: http://www.php.net/serialize
Sorry... a little correction: <?php $data="## /T (KEY1)/V (VALUE1)|| ## /T (KEY2)/V (VALUE2)|| ## /V (VALUE3)/T (KEY3)||"; $data_array=array(); preg_replace(
    array(
    "/\#\#\s*\/T\s*\(([^\)]*)\)\s*\/V\s*\(([^\)]*)\)\s*\|\|/e",
    "/\#\#\s*\/V\s*\(([^\)]*)\)\s*\/T\s*\(([^\)]*)\)\s*\|\|/e"
    ),
    array(
    "\$data_array['\\1']='\\2';",
    "\$data_array['\\2']='\\1';"
    ),
    $data
); print_r($data_array); //see if you get it as expected ?>

« previous php.general (#212617) next »