Forum Moderators: coopster

Message Too Old, No Replies

php Regex

Li'l comma problem

         

Longhaired Genius

4:25 pm on May 4, 2004 (gmt 0)

10+ Year Member



I'm trying to extract the day of the month out of a string, '10' in this case, but, try as I might, I can't get rid of the following comma. Can anybody help?

<?php
preg_match("/(&nbsp;)\d{1,2}(,&nbsp;)/", 'May&nbsp;10,&nbsp;2004<br>15:59', $matches);
echo "$matches[0]";
?>

coopster

4:58 pm on May 4, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Your error lies in that your parentheses are in the wrong places. It's difficult to tell with the smileys on, but it looks like you are probably matching the first
&nbsp;
and the second
&nbsp;
as opposed to the digits before the comma, which is what you want.

Also, if matches is provided, then it is filled with the results of search.

$matches[0]
will contain the text that matched the full pattern,
$matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.

Notice the placement of the parentheses now...

preg_match("/&nbsp;(\d{1,2}),&nbsp/", 'May&nbsp;10,&nbsp;2004<br>15:59', $matches); 
echo $matches[1];

...as well as the correct array index in the $matches array (
$matches[1]
).

Longhaired Genius

5:21 pm on May 4, 2004 (gmt 0)

10+ Year Member



That works! Thanks very much.