Jump to content

[SOLVED] splitting strings


webent

Recommended Posts

Hi, I was hoping someone might be able to tell me if the best way to split a string into multiple strings is to use split? I have read that using preg_split, str_split, and explode are often considered better... I am importing a csv file and one field in particular uses "|" to separate the categories... I need to be able to take the first section and make it say $var1, the second part, if there is one, and make it $var2, and the third part, if there is one, $var3 and throw away any that may follow...

 

Here is one of the field entries for instance, "consumer electronics|phone and telecom|headsets" So say,

$CATEGORIES = "consumer electronics|phone and telecom|headsets";
list($var1, $var2, $var3) = split('[|]', $CATEGORIES);

Link to comment
https://forums.phpfreaks.com/topic/120810-solved-splitting-strings/
Share on other sites

I don't understand why you would want all those variable when you could just have a full array with keys

but two ways I can come up with are

 

1. Explode and Extract

//explode the the categories
$CATEGORIES = "consumer electronics|phone and telecom|headsets";
$cats = explode("|",$cats);
//then extract them all with a prefix "var"
extract($cats, "EXTR_PREFIX_ALL", "var");

 

2. Explode and Foreach it

//explode the categories
$CATEGORIES = "consumer electronics|phone and telecom|headsets";
$cats = explode("|",$cats);
//then loop through and create each variable
$i = 1;
foreach($cats as $cat) {
   $var{$i} = $cat;
   $i++;
}

 

The first one will make variables like this $var_x

I'm sorry if there was any confusion as to what I'm trying to do... I have to insert the split strings into the database under, product_line, product_master_category, and product_category fields...

 

Thank you all for your responses

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.