Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.