Reputation: 737
i get this response from the server:
OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235 OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692
and so on...
This is just one long string with NO carriage return i copied it exactly as received. please note, initial OK can be a different word as well as 0 (at the beginning of the string) can be upto 3 digits number.
this is the pattern that repeats itself:
OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235
i would like to transform it into an array that looks like this:
Array
(
[0] => Array
[1] => OK
[2] => 0
[3] => e3674786a1c5f7a1
[4] => 6162865783958235
[1] => Array
[1] => OK
[2] => 0
[3] => 9589936487b8d0a1
[4] => 6141138716371692
)
How would you go about it? I appreciate your input.
Upvotes: 2
Views: 155
Reputation: 400932
Considering you have that data as a string as input :
$str = <<<STR
OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235
OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692
STR;
A solution would be to explode
that string into separate lines :
$lines = explode("\n", $str);
Edit after the comment and the edit of the OP
Considering the data you receive is on only one line, you'll have to find another way to split it (I think it's easier splitting the data and working on "lines" that working on a big chunk of data at once).
Considering the data you're receiving looks like this :
$str = <<<STR
OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235 OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692
STR;
I suppose you could split it in "lines", with preg_split
, using a regex such as this one :
$lines = preg_split('/SMSGlobalMsgID: (\d+) /', $str);
If you try to output the content of $lines
, it seems quite OK -- and you should now be able to iterate over thoses lines.
Then, you start by initializing the $output
array as an empty one :
$output = array();
And you now have to loop over the lines of the initial input, using some regex magic on each line :
See the documentation of preg_match
and Regular Expressions (Perl-Compatible)
for more informations
foreach ($lines as $line) {
if (preg_match('/^(\w+): (\d+); Sent queued message ID: ([a-z0-9]+) SMSGlobalMsgID:(\d+)$/', trim($line), $m)) {
$output[] = array_slice($m, 1);
}
}
Note the portions I captured, using ()
And, in the end, you get the $output
array :
var_dump($output);
That looks like this :
array
0 =>
array
0 => string 'OK' (length=2)
1 => string '0' (length=1)
2 => string 'e3674786a1c5f7a1' (length=16)
3 => string '6162865783958235' (length=16)
1 =>
array
0 => string 'OK' (length=2)
1 => string '0' (length=1)
2 => string '9589936487b8d0a1' (length=16)
3 => string '6141138716371692' (length=16)
Upvotes: 1