-1

I'm new to php and have a basic question regarding parsing strings.

I have a variable "SKU" whose value is "9897_BLK"

I need to split this into two separate values:

"STYLE" with a value of "9897" AND

"COLOR" with a value of "BLK"

I suppose there's a way to use the underscore to delimit the string. Thanks for your help.

  • `I have a variable "SKU" whose value is "9897_BLK"` so in code `$SKU = "9897_BLK";`? Have you tried anything to separate the data? – chris85 Feb 10 '16 at 01:59

3 Answers3

0

Try explode. This basically separates your string using a delimiter as your first parameter, and the string as the second parameter and returns an array of strings generated. Afterwards you can check if the string was properly parsed or you can just directly assign values just like the one below:

$sku  = "9897_BLK";
$sku_parsed = explode("_", $sku);
$style = $sku_parsed[0];
$color = $sku_parsed[1];

If you want more details, the PHP manual is very accessible and has in-depth examples and use-cases for various scenario.

http://php.net/manual/en/function.explode.php

0

Try this:

$sku  = "9897_BLK";
list($style, $color) = explode("_", trim($sku));
0

In PHP we use an function to split any string with delimiter. You may try the explode function. The explode function return an array as output and the array values are the delimited values respectively. Here is code snippet:

$SKU = "9897_BLK";
$DELIMITED_ARRAY = explode("_", $SKU);
$STYLE = $DELIMITED_ARRAY[0];
$COLOR = $DELIMITED_ARRAY[1];
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42