Dont match the entire expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Dont match the entire expression

Post 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
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Dont match the entire expression

Post 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
Post Reply