Forum Moderators: coopster

Message Too Old, No Replies

Please help, Simple parsing problem

parse text string

         

WhoseDaMan

2:42 pm on Oct 1, 2005 (gmt 0)

10+ Year Member



I am stuck on this simple problem. I have a text string (currently as one long variable) which is in the format:

field_name1="value1" field_name2="value2" field_name3="value3" field_name4="value4" field_name5="value5" field_name6="value6" field_name7="value7"

This is all in one chunk of text. How can I parse this to get each field as an individual variable (e.g. $field_name1)?

I am really stuck on this and any help would be appriciated.

Longhaired Genius

3:15 pm on Oct 1, 2005 (gmt 0)

10+ Year Member



Explode [uk.php.net] is what you need. You could explode the string on "space" to put the names and values into and array. Then use foreach [uk.php.net] on the array to explode the elements on "=" into individual 2-term arrays, then assign [0] of these arrays to a variable and [1] to the value.

You might also need to use trim [uk.php.net] to get rid of any stray carriage-returns.

mcibor

9:23 pm on Oct 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or you could do such a trick:

Change the string to such string: $field_name1="value1"; $field_name2="value2";

$string = '$'.str_replace(" ", '; $', $string). ';';

And execute it.

eval($string);

You've got what you wished for.
However with this function you would need to check, before executing it, if the data is in the correct form, so that nobody does any harm to your program:
This is the example of harmful code in the file you read:

unlink(".");

I prefer not to test it on my computer :)

Hope this helps
Michal Cibor

And Welcome to WebmasterWorld!

javier enithost

11:47 pm on Oct 1, 2005 (gmt 0)



Hi :

This can solution completely your problem:

$str .= " ";
$all = preg_split("/([\=\"][\"\s])/", $str );
while (count($all) > 1) {
$var = array_shift( $all );
$value = array_shift( $all );
${$var} = $value;
}

Regards

WhoseDaMan

4:37 am on Oct 4, 2005 (gmt 0)

10+ Year Member



Thank you so much for your replies. The last solution worked perfect.

the problem is solved and is working perfectly. the explode method first suggested did not work because the values contained spaces and the values got split into different elements in the array too.

this board is great! thank you guys for your help!