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.

Link to comment
Share on other sites

[...]  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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.