1

I'm trying to extract the start date April 1, 2017 using preg_match_all() from the following line where Both date is dynamic.

for April 1, 2017 to April 30, 2017

$contents = "for April 1, 2017 to April 30, 2017";
if(preg_match_all('/for\s(.*)+\s(.*)+,\s(.*?)+ to\s[A-Za-z]+\s[1-9]+,\s[0-9]\s/', $contents, $matches)){
    print_r($matches);
}
3
  • 1
    You may use something like preg_match_all('~\b[a-z]+\s*\d{1,2},\s*\d{4}\b~i', $contents, $matches), see the regex demo. Commented Dec 5, 2019 at 11:41
  • 1
    Or perhaps match the whole string with 2 capturing groups \bfor\h+(\w+\h+\d{1,2},\h+\d{4})\h+to\h+((?1))\b regex101.com/r/LCvlqW/1 Commented Dec 5, 2019 at 11:43
  • It's working but you can elaborate in details in answer. Commented Dec 5, 2019 at 11:52

1 Answer 1

2

If you want to match the whole string and match the 2 date like patterns you could use 2 capturing groups.

Note that it does not validate the date itself.

\bfor\h+(\w+\h+\d{1,2},\h+\d{4})\h+to\h+((?1))\b

In parts

  • \bfor\h+ Word boundary, match for and 1+ horizontal whitespace chars
  • ( Capture group 1
    • \w+\h+\d{1,2} Match 1+ word chars, 1+ horizontal whitespace chars and 1 or 2 digits
    • ,\h+\d{4} Match a comma, 1+ horizontal whitespace chars and 4 digits
  • ) Close group
  • \h+to\h+ Match to between 1+ horizontal whitspace chars
  • ( Capture group 2
    • (?1) Subroutine call to capture group 1 (the same pattern of group 1 as it is the same logic)
  • ) Close group
  • \b Word boundary

Regex demo

For example

$re = '/\bfor\h+(\w+\h+\d{1,2},\h+\d{4})\h+to\h+((?1))\b/';
$str = 'for April 1, 2017 to April 30, 2017';
preg_match_all($re, $str, $matches);
print_r($matches)

Output

Array
(
    [0] => Array
        (
            [0] => for April 1, 2017 to April 30, 2017
        )

    [1] => Array
        (
            [0] => April 1, 2017
        )

    [2] => Array
        (
            [0] => April 30, 2017
        )

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

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.