TaylorOtwell
TaylorOtwell

Reputation: 7337

Extract parts of string that match regular expression groups?

Not entirely sure this is possible, but hoping to be pleasantly surprised.

I have a regular expression that looks like this:

$pattern = '#post/date/(\d\d\d\d)-(\d\d)-(\d\d)#';

And, I even have a string that matches it:

$string = 'post/date/2012-01-01';

Of course, I don't know the exact pattern and string beforehand, but they will look something like this.

I need to end up with an array that looks like this:

$groups = array('2012', '01', '01);

The array should contain the parts of the string that matched the three regular expression groups that are within parentheses. Is this possible?

Upvotes: 2

Views: 2169

Answers (4)

hakre
hakre

Reputation: 197832

If you're looking for something concise:

$matches = sscanf($string, '%*[^0-9]%d-%d-%d');

makes $matches:

array(3) {
  [0]=> int(2012)
  [1]=> int(1)
  [2]=> int(1)
}

Upvotes: 1

Shakti Singh
Shakti Singh

Reputation: 86406

Not a regular expression but will do what you want to achieve

<?php
$string = 'post/date/2012-01-01';
$date= basename($string);
$array=explode('-',$date);
print_r($array);
?>

The output array will look like this

Array
(
    [0] => 2012
    [1] => 01
    [2] => 01
)

Upvotes: 2

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

$str = 'post/date/2012-01-01';
preg_match('#post/date/(\d+)-(\d+)-(\d+)#', $str, $m);
array_shift($m);
$group = $m;
print_r($group);

Output

Array
(
    [0] => 2012
    [1] => 01
    [2] => 01
)

Upvotes: 1

mishu
mishu

Reputation: 5397

those things between parentheses are subpatterns and you can get the results for each of them when you apply the regex. you can use preg_match_all like this

$string = 'post/date/2012-01-01';
$pattern = '#post/date/(\d\d\d\d)-(\d\d)-(\d\d)#';
preg_match_all($pattern, $string, $matches);
$groups = array($matches[1][0], $matches[2][0],$matches[3][0]);
echo '<pre>';
print_r($groups);
echo '</pre>';

sure, this is an example that just shows the behavior, you will need to check first if the string matched the pattern and if it did, how many times.. you can see that piece of code working here: http://ideone.com/zVu75

Upvotes: 6

Related Questions