Muisca
Muisca

Reputation: 153

preg_replace int, decimal, negative numbers

replace ALL numbers. negative, positive, separated by comma, point, etc

I have

  $txt = "car -12 and dog 3.1416 and cat 98 and 4,12 and flowers = 0.1 and -75";

I like

$txt = "car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM";

Please help

Upvotes: 0

Views: 1002

Answers (2)

mickmackusa
mickmackusa

Reputation: 47874

Code: (Demo)

$txt = "car -12 and dog 3.1416 and cat 98 and 4,12 and flowers = 0.1 and -75";
echo "EXPECT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM\n";
echo "OUTPUT: ",preg_replace('~-?\d*[,.]?\d+~','NUM',$txt);

Output:

EXPECT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM
OUTPUT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM

Breakdown:

~      #pattern delimiter
-?     #match zero or one hyphen
\d*    #match zero or more digits
[,.]?  #match zero or one character in list: comma or dot
\d+    #match one or more digits
~      #pattern delimiter

If this pattern does not perform as desired on all of your input strings, please update your question to include these troublesome strings and leave me a comment and I'll update my answer.

*notes:

  • I don't use any capture groups because capture groups cost more "steps" (slow down the regex engine).
  • A . inside of a character class [.] does not need to be escaped to be treated literally. Using . outside of a character class will need to be escaped in some manner, otherwise it will be treated as "any non-newline character".

Upvotes: 0

Tianwen Sun
Tianwen Sun

Reputation: 43

$a = preg_replace('/(-)?[0-9]+(.)?[0-9]+/','NUM',$txt);

Upvotes: 1

Related Questions