Search code examples
regexpreg-match

Regex - get string after full date and before standard text


I'm stuck on another regex. I'm extracting email data. In the below example, only the time, date and message in quotes changes.

Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.

How can I get the message only if I need to start with the positive lookbehind, (?<=Message Received ) to begin searching at this particular point of the data? The message will always start and end with quotes but the user is able to insert their own quotes as in the second example.


Solution

  • You can just use a negated charcter class in a capturing group:

    /Message Received.*?"([^\n]+)"/
    

    Snippet:

    $input = 'Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
    Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.}';
    
    preg_match_all('/Message Received.*?"([^\n]+)"/', $input, $matches);
    
    foreach ($matches[1] as $match) {
        echo $match . "\r\n";
    }
    

    Output:

    > Hello. My name is John Smith
    > Hello. My name is "John Smith"