John Davidson

php - Regex matching multiple lines multiple times without matching date and time

0 comments
Message:


Regex matching multiple lines multiple times


\s*([^:]+?)\s*:\s*(.*(?:\s*(?!.*:).*)*)\s* 

This solution matches the date and time string.


How do I modify the above solution so that the date and time is included with the Description: header?


Name: John Doe

Age: 23

Primary Language: English

Description: This is a multiline
description field that I want
to capture Fri, 02 Sep 2022 14:46:45 -0500

Country: Canada


My Answer:
To modify the regex pattern to include the date and time with the Description header, you can use the following pattern:

php
Description: (.*(?:\n(?!.*:).*)*)\n(.*)


This pattern will match the Description header along with the date and time string that follows it. Here is how you can use it in PHP:

php
$pattern = '/Description: (.*(?:\n(?!.*:).*)*)\n(.*)/';
$string = 'Name: John Doe
Age: 23
Primary Language: English
Description: This is a multiline_description field that I want to capture Fri, 02 Sep 2022 14:46:45 -0500
Country: Canada';

preg_match($pattern, $string, $matches);

$description = $matches[1];
$dateAndTime = $matches[2];

echo "Description: " . $description . "\n";
echo "Date and Time: " . $dateAndTime . "\n";


This code will output:


Description: This is a multiline_description field that I want to capture
Date and Time: Fri, 02 Sep 2022 14:46:45 -0500

Rate this post

4 of 5 based on 6064 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us