faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 1 of 3 people (33%) answered Yes

Entry

[a|b|c][d|e|f][g|h|i] How can I extract the data from this format?

Jun 11th, 1999 07:00
Nathan Wallace, Rod


The easiest way to split a single string unto multiple strings is using
explode().

Unfortunately, in this case you have delimitation using more than one
character (the []).  So we will need to strip those out.

$data = '[a|b|c][d|e|f][g|h|i]';

$bracketed=explode("\]\[",$data);

// $bracketed is now an array like this
// array('[a|b|c', 'd|e|f', 'g|h|i]')

Then you'll need to step through $bracketed (however works best for you)
and apply the following to each of the elements:

$temp=ereg_replace("\[|\]","",$bracketed[$i]);

that will remove any remaining "[" or "]".

Now, explode again on the pipes:

$usable=explode ("|",$temp);

you will have an array $usable containing the elements of one of the []
parts of the data.  For example: array(a, b, c)

Obviously, you'll need to set up the proper loops, but how you do that
depends on how you want the final data to be available (e.g. all in one
array, unique variable names, one array for each section, etc)