Reputation: 146
I need to split strings like:
Some description art.nr: 4457 72 1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34
The result I need is:
To make it extra complex, the first part is optional, but the other parts always start with '1x' or so.
I tried many regexp, but I cannot get it to work. I can use preg_split() with something like /\s?\d+x\s/
as workaround, but that is really dirty, although it splits nicely.
Even when only trying to split parts 2 till 5, I can't get it right.
I have tried many regexp-patterns with preg_match_all() in php on the least complex string:
1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34
The following patterns came closest:
/(\d+x\s+.+?)(\s+(\d+x\s+.+?(?!\s\d+x\s)))+/i
/(\d+x\s+.+)(\s+(\d+x\s+.+))+/i
I think it should be something like: /((\s+)?(\d+x\s+.+(?!\s\d+x\s)))+/i
but it does not do the job.
And the simple ones like /(\s?\d+x\s+.+)+/i
just returns the full string or only the first chars /(\s?\d+x\s+.+?)+/i
I tried these (and many other variants) on:
What am I doing wrong? It drives me crazy; this is really not my first regexp!
(and how to get it working for the full string with the optional first part)
Thanks in advance!
Upvotes: 2
Views: 443
Reputation: 18357
Why don't you use this regex for splitting instead of so much complicated ones?
\s+(?=\d+x\s+)
$s = "Some description art.nr: 4457 72 1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34";
var_dump(preg_split("/\s+(?=\d+x\s+)/", $s));
Prints,
array(5) {
[0]=>
string(32) "Some description art.nr: 4457 72"
[1]=>
string(36) "1x ACOUCH 90X200 NICE GRAY (3 colli)"
[2]=>
string(19) "1x matras 85x205x12"
[3]=>
string(30) "2x matras 80x190x11 Some specs"
[4]=>
string(39) "14x Premium otherproduct 90x200x23 HR34"
}
Upvotes: 2
Reputation: 5202
A long-winded way of doing what Pushpesh' regex does:
$str = "Some description art.nr: 4457 72 1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34";
$words = explode(" ", $str);
$i = 0;
foreach($words as $word){
if(preg_match("/^\d+x$/", $word)){
$i++;
}
$array[$i][] = $word;
}
foreach($array as $words){
$split[] = implode(" ", $words);
}
var_dump($split);
Output:
array(5) {
[0]=>
string(32) "Some description art.nr: 4457 72"
[1]=>
string(36) "1x ACOUCH 90X200 NICE GRAY (3 colli)"
[2]=>
string(19) "1x matras 85x205x12"
[3]=>
string(30) "2x matras 80x190x11 Some specs"
[4]=>
string(39) "14x Premium otherproduct 90x200x23 HR34"
}
Upvotes: 1