简体   繁体   中英

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?

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

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
)
$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
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM