Jump to content

Finding string within a string with preg_match_all


python72

Recommended Posts

I am looking for a date within larger string, lets say the date is December 4, 2010.

To find it I use pattern and function below:

 

$Pattern='/[(January|February|March|April|May|June|July|August|September|October|November|December)] \d, \d\d\d\d/i';
preg_match_all($Pattern, $String, $Matches, PREG_OFFSET_CAPTURE, $NumberPosition);

 

The function finds the dates within the string but to my supprise the result I get in $Matches is: r 4, 2010

What I would like to get is: December 4, 2010 but don't know how it should be fixed. I thought that with the pattern I am using but obviously that is not the case.

[...]  means a character set. [abc] will match "a", "b", or "c"; [(a|b|c)] will match "a", "b", "c", "(", "|", and ")".

In other words, the (|)s mean nothing besides what they literally are.

 

Since you don't want a character set, remove the []s.

 

Also, what about a string

December 14, 2010

The day has two digits.

I guess I have to follow the previous search with check for NULL in $Matches, I believe that there would be nothing stored in $Matches if string was not found so I think the if statement should look like this:

 

if ($Matches == Null){
$Pattern='/(January|February|March|April|May|June|July|August|September|October|November|December) \d\d, \d\d\d\d/i';
$Pattern='/\d, \d\d\d\d/';
preg_match_all($Pattern, $String, $Matches, PREG_OFFSET_CAPTURE, $NumberPosition);
}

 

Would this be right?

Did not realize that I can have optional attributes in my pattern but after reading some stuff I guess my pattern would look like this:

$Pattern='/(January|February|March|April|May|June|July|August|September|October|November|December) (\d)?\d, \d\d\d\d/i';

Please correct me if I am wrong.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.