0

I search before ask, but I what I've tested doesn't work. I have following string:

2016-07-31 00:32:29 debian-8gb-sfo2-01 gamed: notice : 

I want to know how can I extract date from this string. The full regex (missing the date regex) returns the following:

Array
(
    [0] => 2016-07-31 00:32:29 debian-8gb-sfo2-01 gamed: notice : formatlog:gshop_trade:userid=1792:db_magic_number=1744:order_id=23727:item_id=47494:expire=0:item_count=1:cash_need=1:cash_left=99976272:guid1=0:guid2=0
    [1] => 2016-07-31 00:32:29 debian-8gb-sfo2-01 gamed: notice :
    [2] => 1792
    [3] => db_magic_number=1744:order_id=23727:
    [4] => 47494
    [5] => 0
    [6] => 1
    [7] => 1
    [8] => 99976272
)

It's correct, but the desire output is:

Array 
(
        [1] => 2016-07-31 00:32:29
        [2] => 1792
        [3] => db_magic_number=1744:order_id=23727:
        [4] => 47494
        [5] => 0
        [6] => 1
        [7] => 1
        [8] => 99976272
)

The current code:

if (strpos($line, 'gshop_trade:userid=1792:') > 0) {
    if (!preg_match('/(.*)\sformatlog:gshop_trade:userid=(\d+):(.*)item_id=(\d+):expire=(\d+):item_count=(\d+):cash_need=(\d+):cash_left=(\d+).*$/', $line, $d)) {
        // error occured
    }
   echo '<pre>';
   print_r($d);
}
6
  • 1
    What exactly is the regex you're using? You make mention of it, but don't display it. Commented Feb 7, 2018 at 16:26
  • Please edit your question, and add the code used to extract the date. Judging by your data, you add group 0 to the output. Commented Feb 7, 2018 at 16:27
  • @Seth I added the code. Commented Feb 7, 2018 at 16:27
  • You didn't capture date time separately at all: /\s*(\S+\s+\S+).*\sformatlog:gshop_trade:userid=(\d+):(.*)item_id=(\d+):expire=(\d+):item_count=(\d+):cash_need=(\d+):cash_left=(\d+).*$\K/ Commented Feb 7, 2018 at 16:35
  • What about using \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|\b([^\W\d]+)\s*=\s*\K\d+? Commented Feb 7, 2018 at 16:37

2 Answers 2

2
/([\d-: ]+)\s.*\sformatlog:gshop_trade:userid=(\d+):(.*)item_id=(\d+):expire=(\d+):item_count=(\d+):cash_need=(\d+):cash_left=(\d+).*$/

You were using a capture group around items that you didn't wish to capture at the start, the group ([\d-: ]+) should capture the date correctly

See the demo

Sign up to request clarification or add additional context in comments.

1 Comment

Yup! Work perfect. Thank you.
0

Try this. If you want to match exactly the date from any string in the format YYYY-MM-DD use the below Regular expression

[0-9]{4}-[0-9]{2}-[0-9]{2}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.