This is kind of a follow on from this post: Regex for splitting params out using preg_match
I have this string 1 0 61 12345678 sierra007^7 0 0 123.123.123.123:524 26429 25000
and I need to get each element. It was suggested I use explode which was a great simple solution but now I need to allow spaces in one of the fields.
Someone else posted this regex:
/^([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+(\S+)\s+([-0-9])\s+([-0-9]+)\s+([-0-9.:]+)\s+([-0-9.]+)\s+([-0-9.]+)/mx
That does everything else and I was wondering if it could be modified to allow spaces in field 5 (sierra007^7
). The only advice I can offer is that the rest of the fields are always numeric (or a colon as you can see) before and after field 5. Is this possible with 1 regex statement or do I need to parse it in PHP and fudge it together?
EDIT: For example, field 5 could be sierra007^7
OR si erra007^7
or si er ra007^7
开发者_如何学Go. It would know that it came across field 5 as its the only one that contains a-zA-Z characters. It would know where field 5 ends because field 6 only contains 0-9 characters.
Thanks.
Why not use explode, like the other thread. And count the number of items in the array. If more items are in the array, you put item 5 + any number too high together again with implode.. Eg. your normal row has 10 items. If the resulting explode has 15 items, you:
implode(" ",array_slice($array,5,(count($array)-10)));
If the number of fields never changes, and there's always a value for each field, you can do it using code below:
$fields = explode (' ', $str);
$defaultNumFields = 10;
if (count($fields) > $defaultNumFields) {
for ($i = 5; $i < (count($fields) - $defaultNumFields) + 5; $i++) {
$field[4] .= ' '.$field[$i];
unset($field[$i]);
}
}
$fields = array_values($fields);
That should do it. I might have mis-calcuated and you might need to change the +4 to a +5, test it on a few strings and let me know.
精彩评论