Street and (maybe) Date

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

Moderator: General Moderators

Post Reply
waquner
Forum Newbie
Posts: 2
Joined: Wed Mar 25, 2009 1:32 pm

Street and (maybe) Date

Post by waquner »

Hey,

I want to extract a Street and a Date (not always) from a String via preg_match.

Example strings:

Code: Select all

mpark Musterstreet 12 9:00
or

Code: Select all

mpark Musterstreet 12
I tried different regexes, but they matched either the string with time or just without the time, problem seems to be the space between
the street and the time, which isn't there, when there's no time. I tried

Code: Select all

mpark (.*)\s?((.{1,2}):(.{1,2}))?
or

Code: Select all

mparkplatz (.*)\s?((\d*):(\d*))?
or

Code: Select all

mparkplatz (.*) ((\d*):(\d*))?
Any ideas?
TIA,
waquner
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Street and (maybe) Date

Post by prometheuzz »

waquner wrote:...

Any ideas?
TIA,
waquner
I have no idea what you're trying to match, and also have no idea what form your input string can take. A lot more details and examples are required.
waquner
Forum Newbie
Posts: 2
Joined: Wed Mar 25, 2009 1:32 pm

Re: Street and (maybe) Date

Post by waquner »

sorry, i though it was clear...

the input string will look like

Code: Select all

mpark <somestring> <HH:ii>
where mpark is always fixed (so don't mind about it) and the other tokens within the <> are variable

or the same without the time

Code: Select all

mpark <somestring>
and what im trying to match is just the "<somestring>" and if existent the time "<HH:ii>"

I know, i can explode the string by a space, but i want (or have to) use regex
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Street and (maybe) Date

Post by prometheuzz »

Try this:

Code: Select all

$tests = array(
  'ignore mpark Musterstreet 12 9:00 ignore',
  'ignore mpark Musterstreet 12 ignore'
);
foreach($tests as $t) {
  if(preg_match('/mpark\s+(\S+(?:\s+\d+)?)(?:\s+(\d+:\d+))?/', $t, $matches)) {
    print_r($matches);
  }
}
atonalpanic
Forum Commoner
Posts: 29
Joined: Mon Mar 02, 2009 10:20 pm

Re: Street and (maybe) Date

Post by atonalpanic »

waquner wrote:I know, i can explode the string by a space, but i want (or have to) use regex
I know you said you have to use regex, but just as an FYI, explode is much faster than regex.
Post Reply