Nirdesh Kumawat
Nirdesh Kumawat

Reputation: 406

extract value from string using php

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);
}

Upvotes: 1

Views: 56

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

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
        )

)

Upvotes: 2

Related Questions