-2

I need to parse a string and get the numbers between 2 delimiters. I need to be sure they're numbers. I tried something like this but doesn't work as expected.

if (preg_match_all("/[^0-9](?<=First)(.*?)(?=Second)/s", $haystack, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

What's wrong with the regex?

Giorgio
  • 1,505
  • 1
  • 26
  • 52
  • 1
    What is the input, what do you expect and what do you get? – jeroen Aug 13 '13 at 18:39
  • 1
    Jesus, that depends. What's in `$haystack`? What comes out in `$result`? What would you like to come out in `$result`? – FrankieTheKneeMan Aug 13 '13 at 18:40
  • 1
    How did you come up with `[^0-9]` at the start, why are you using lookarounds, and not just the literal delimiters and a number match in between? – mario Aug 13 '13 at 18:40

2 Answers2

1

Huh, that's almost the one I supplied to your other question xD

Change the (.*?) to ([0-9]+)

if (preg_match_all("/(?<=First)([0-9]+)(?=Second)/s", $haystack, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

.*? will match any character (except newlines) and to match only numbers in between your delimiters "First" and "Second", you will need to change it to [0-9]. Then, I assume that there can't be nothing in between them, so we use a + instead of a *.

I'm not sure why you used [^0-9] in the beginning. Usually [^0-9] means one character which is not a number, and putting it there doesn't really do something useful, at least in my opinion.

Community
  • 1
  • 1
Jerry
  • 67,172
  • 12
  • 92
  • 128
  • @Martijn I just saw your suggested edit and you should read [this](http://stackoverflow.com/q/16621738/1578604) to see why I used `[0-9]` instead of `\d`. – Jerry Aug 13 '13 at 19:11
0

You can use [0-9] or \d to ensure that the characters between the delimiters are numbers. using this you also won't need the lazy quantifier (unless your delimiters are actually numbers, too):

preg_match_all("/[^0-9](?<=First)(\d*)(?=Second)/s", $haystack, $result)

Or

preg_match_all("/[^0-9](?<=First)([0-9]*)(?=Second)/s", $haystack, $result)
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299