Page 1 of 1

Dont match the entire expression

Posted: Sun Jun 08, 2008 6:18 pm
by SidewinderX

Code: Select all

       preg_match('#(\d+)[,.-\s]?(\d+)[,.-\s]?(\d+)#', $input, $matches);
       print_r($matches);
Will print:

Code: Select all

Array
(
    [0] => 2,4,2008
    [1] => 2
    [2] => 4
    [3] => 2008
)
 
How do I just match this?

Code: Select all

Array
(
    [0] => 2
    [1] => 4
    [2] => 2008
)
Thanks,
John

Re: Dont match the entire expression

Posted: Mon Jun 09, 2008 4:19 am
by prometheuzz
SidewinderX wrote:

Code: Select all

       preg_match('#(\d+)[,.-\s]?(\d+)[,.-\s]?(\d+)#', $input, $matches);
       print_r($matches);
Will print:

Code: Select all

Array
(
    [0] => 2,4,2008
    [1] => 2
    [2] => 4
    [3] => 2008
)
 
How do I just match this?

Code: Select all

Array
(
    [0] => 2
    [1] => 4
    [2] => 2008
)
Thanks,
John
No AFAIK, with preg_match(...) the entire match is stored in index 0 of the $matches array, there's no way around that.
Can't you just split your input string on your character class?

Code: Select all

$input = "2-4-2008";
$matches = preg_split('/[-\s,.]/i', $input);
print_r($matches);
Also, I recommend for clarity you to put the hyphen at the start or at the end of your character class when you want to match it, otherwise, it might be seen as the meta character of a character range.

HTH