Page 1 of 1

Street and (maybe) Date

Posted: Wed Mar 25, 2009 2:00 pm
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

Re: Street and (maybe) Date

Posted: Wed Mar 25, 2009 4:04 pm
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.

Re: Street and (maybe) Date

Posted: Wed Mar 25, 2009 4:39 pm
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

Re: Street and (maybe) Date

Posted: Thu Mar 26, 2009 2:44 am
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);
  }
}

Re: Street and (maybe) Date

Posted: Thu Mar 26, 2009 2:08 pm
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.