2

Consider the following string:

$text = "Dat foo 13.45 and $600 bar {70} and {8}";

I need to label all numbers in $text, except for when they are between curly braces. I now have this:

echo preg_replace("([0-9]+(?:\.[0-9]+)?)","{NUMBER:$0}",$tweet);

which outputs:

Dat foo {NUMBER:13.45} and ${NUMBER:600} bar {{NUMBER:70}} and {{NUMBER:8}}

However, the desired output is:

Dat foo {NUMBER:13.45} and ${NUMBER:600} bar {70} and {8}

where numbers between { and } are ignored. Is it possible to expand the regex to ommit curly braces or is another solution needed here?

Any help would be greatly appreciated :-)

Pr0no
  • 3,910
  • 21
  • 74
  • 121
  • 3
    You can show your great appreciation simply by accepting answers. Also consider investigating the syntax. This is your fourth plzsendtehregex question in a row; specifically lookaround syntax has been explained to you before. -- SA: [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for tools, or [RegExp.info](http://regular-expressions.info/) for a tutorial. – mario Feb 10 '12 at 21:41

1 Answers1

3

Try using lookaheads/lookbehinds to find numbers without {}.

NOTE: Make sure to enclose your regex in delimiters (such as /).

echo preg_replace("/(?<!{)([0-9]+(?:\.[0-9]+)?)(?!})/","{NUMBER:$0}",$tweet);

DEMO: http://codepad.org/7ai0px2i

(?<!{) means "not preceded by a {", and (?!}) means "not followed by a }".

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • This is great - it almost works :) However, if for $tweet = "foo 40 bar {baz40}" it doesnt. The output is "foo {NUMBER:40} bar {baz {NUMBER:4} 0}". In other words: it solely ignores numbers between curly braces, but doesn't if there are other characters between the braces next to the number(s). Is it possible to make the regex ignore * everything * that is between curly braces so that, in this example, the output would be foo {NUMBER:40} bar {baz40}? – Pr0no Feb 10 '12 at 22:59
  • @Reveller: I'm not sure. Because lookbehinds needs to be a fixed length. You could use `preg_replace_callback` instead of lookarounds, and then in the callback detect if it's in curly braces. – gen_Eric Feb 11 '12 at 17:20