1

I need to get all operators (arithmetic, comparison, logical...) in a string...

((value+10)*10)>=300   ||   (array[key]-20==0&&"foo==bar"!=="")

...and add a single whitespace before and after them (if doesn't already exists)...

((value + 10) * 10) >= 300 || (array[key] - 20 == 0 && "foo==bar" !== "")

...ignoring what is between quotes or single quotes.

Aditional rules:

  • add space only before pre-in/decrement operators
  • add space only after post-in/decrement operators

Sounds easy but I can't get how I could do it using regex in PHP. Thanks if someone can help!

I'm trying to do something like $str = preg_replace('(?<=[\w\]\)\s\"\'])\!=(?=[\w\]\)\s\"\'])', ' != ', $str); for every operator, but I don't think it's a good idea.

4
  • 1
    I would love to repair your regex if you made one. Commented Jan 27, 2016 at 19:46
  • @MarinoBoscoloNeto - I'd still stick that code in your post just so it demonstrates that you've made the effort. Commented Jan 27, 2016 at 19:51
  • Should (-20+3) be (- 20 + 3) or (-20 + 3)? Commented Jan 27, 2016 at 20:01
  • @WashingtonGuedes (-20 + 3) is better Commented Jan 27, 2016 at 20:04

2 Answers 2

2

this pattern works with PCRE Engines, which I believe php is

"[^"\r\n]*"(*SKIP)(*F)|\s*([\-\/+*=|<>!&]+)\s*

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

I would use three regexes:

<?php

$str = <<<EOT
(-20+3)
((value+10)*10)>=300   ||   (array[key]-20==0&&"foo==bar"!=="")
EOT;

$str = preg_replace('/("[^"]*"|\([^+=&<>|*\/\\%\w\d-]*|-?\d+|[\w[\]]+|\))/', ' $1 ', $str);
$str = preg_replace('/(?<=\() +| +(?=\))/', '', $str);
$str = preg_replace('/ +/', ' ', $str);

print_r($str);

Check it live here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.