tags:

views:

45

answers:

2

So the user may search for "10 mbit" after which I want to capture the "10" so I can use it in a speed-search rather than a string-search. This isn't a problem, the below regexp does this fine:

if (preg_match("/(\d+)\smbit/", $string)){ ... }

But, the user may search for something like "10/10 mbit" or "10-100 mbit". I don't want to match those with the above regexp - they should be handled in another fashion. So I would like a regexp that matches "10 mbit" if the number is all-numeric as a whole word (i.e. contained by whitespace, newline or lineend/linestart)

Using lookbehind, I did this:

if (preg_match("#(?<!/)(\d+)\s+mbit#i", $string)){

Just to catch those that doesn't have "/" before them, but this matched true for this string: "10/10 mbit" so I'm obviously doing something wrong here, but what?

A: 

You lookback assertion is negative. It tells the string should not be preceded by /

So the / is matched inside the string (as the regex cannot match only "10" : you forbid it explicitely with the assertion). Maybe you wanted a positive lookbehind?

Savageman
No, the string 10 (matched by (\d+)) should not be preceded by "/". If it is, the search should return false. But it returns true.
Sandman
My bad, you're right. The assertion is before the \d+ statement. I'll look further.
Savageman
+1  A: 

If the slash or hyphen is the only thing you care about, this should do it:

'#(?<![\d/-])(\d+)\s+mbit#i`

The problem with your regex is that \d+ is only required to match one digit. It can't match the 10 in 10/10 mbit because it's preceded by a slash, but the 0 isn't. To make sure it matches from the beginning of the number, you have to include \d in the list of things it can't be preceded by.

Alan Moore
Thanks! Yeah, I totally missed the entire matching on one digit.
Sandman