简体   繁体   中英

split strings into nested array by matching sub string

I need to split a string into a nested array something like this . Small subset of the actual data

  • There is no fixed size, code could be aaa100 and bbbbbbbb100
  • No fixed char to split on

A similar problem is with converting file path to array but I dont have anything like / to split on.

Use case:

Product import with a few thousand products. Each product code is made up with something like the following:

xxx product type
yyy size
zzz colour

So you have codes like xxxx , xxxxyy , xxxxzz or xxxxyyzz .

AAA100B // product type AAA with size 100 and colour blue
AAA200B // product type AAA with size 200 and colour blue
AAA100G // product type AAA with size 100 and colour green
BBB100B // product type BBB with size 100 and colour blue

Some do not have colour, others don't have size. Possible that some will not have 'matches' and just be a lone code.

Edit

The last char (or two) is normally a colour. Colours can be any of the following. (Colour code will never anywhere except the end of the string)

BK, GY
B, G, O, P, R, S

numbers are assumed to be the size, if the number is in the form 00-00 its lenght/width, else its a single size 00

Edit

Rough start to the problem, virtually there (expand and merge are part of the framework so just hacked them in there) http://codepad.viper-7.com/Wp19g2

Hmm, I guess the obvious (yet somewhat inefficient) way would be to take your code string, loop through the letters till you reach a number (recording all the letters up to that point as your product type), when you reach a number record that value and every number after it till you reach a letter again, and begin recording the color. This, of course, assumes that the color and product type does not include numbers!

$product_size = ""; $product_type = ""; $product_color = "";
for ($i = 0; $i < strlen ( $code ); $i++ ) {
     if ( !is_numeric ( $code [ $i ] ) ) { 
          if ( $product_size == "" ) $product_type .= $code [ $i ];
          else $product_color .= $code [ $i ]
     } else $product_size .= $code [ $i ];
}

Its a good design choice to have a separator though. One problem with my solution is that if there is no product size then it will never record a color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM