1

I have a string:

2014-12-06 01:08:14 Andrew (76561198093241035) killed Moraiti () with weapon hgun_PDW2000_F

I need to be able to seperate this string into its seperate parts like so:

2014-12-06 01:08:14
Andrew
(76561198093241035)
Moraiti
hgun_PDW2000_F

The problem is I don't exactly how many characters each item will have. Is this even possible?

Ricky Barnett
  • 1,130
  • 3
  • 15
  • 32
  • That's a little bit complicated if you don't have a 'blacklist' of words or something like that to detect where to split the string! – Rizier123 Dec 06 '14 at 19:33
  • 2
    What would if I told you that it would always begin with a data timestamp like so `2014-12-06 01:08:14` And `(76561198093241035)` would always be 19 characters long. And the words `Killed` `with` `weapon` would never change – Ricky Barnett Dec 06 '14 at 19:39
  • It would help do get the first string but not the other ones! because you need a pattern to detect/ say where to split the string! – Rizier123 Dec 06 '14 at 19:40
  • Which parts of the string will allways be there? – baao Dec 06 '14 at 22:56

2 Answers2

1

You can use regular expressions:

$pat = '/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (.+?) (\((?:\d{17}|)\)) killed (.+?) (\((?:\d{17}|)\)) with weapon (.+)$/';
$str = '2014-12-06 01:08:14 Andrew (76561198093241035) killed Moraiti () with weapon hgun_PDW2000_F';
preg_match($pat, $str, $matches);
var_dump($matches);
array(7) {
  [0]=>
  string(91) "2014-12-06 01:08:14 Andrew (76561198093241035) killed Moraiti () with weapon hgun_PDW2000_F"
  [1]=>
  string(19) "2014-12-06 01:08:14"
  [2]=>
  string(6) "Andrew"
  [3]=>
  string(19) "(76561198093241035)"
  [4]=>
  string(7) "Moraiti"
  [5]=>
  string(2) "()"
  [6]=>
  string(14) "hgun_PDW2000_F"
}
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

You could also use explode to convert the string into an array. With the string you specified, you would use a space as the delimiter and then you could get the various elements of the array.

Example:

$str = '2014-12-06 01:08:14 Andrew (76561198093241035) killed Moraiti () with weapon hgun_PDW2000_F';
$array = explode(' ', $str);

echo $array[0].' '.$array[1].PHP_EOL;
echo $array[2].PHP_EOL;
echo $array[3].PHP_EOL;
echo $array[5].PHP_EOL;
echo $array[9].PHP_EOL;

Result:

2014-12-06 01:08:14

Andrew

(76561198093241035)

Moraiti

hgun_PDW2000_F

If you want to use other parts of the array, use var_dump($array); to figure out which ones,

Community
  • 1
  • 1
SameOldNick
  • 2,397
  • 24
  • 33