hillz
hillz

Reputation: 547

How to use preg_replace to replace texts outside double single-quote?

I have a text file like this:

ip_rule '100 120 16.54'
qos_rule '8074 4462'
info 'Updated on 2015'

And I want that text to be like this:

ip_rule='100 120 16.54'
qos_rule='8074 4462'
info='Updated on 2015'

So it only replaces the spaces outside of '' and change them to the equal sign =. How can I do that with PHP, I've tried replacing them with str_replace but it replaces the entire spaces.

Upvotes: 2

Views: 144

Answers (1)

chris85
chris85

Reputation: 23892

You can use (*SKIP)(*FAIL) to skip a rule. For example in your current example this will skip anything in single quotes, then find any horizontal spaces (if there can be multiple and it should only be replaced with one =s use the + quantifier):

'.*?'(*SKIP)(*FAIL)|\h

Demo: https://regex101.com/r/umaQdY/1

PHP Usage:

echo preg_replace("/'.*?'(*SKIP)(*FAIL)|\h/", '=', "ip_rule '100 120 16.54'
qos_rule '8074 4462'
info 'Updated on 2015'");

PHP Demo: https://eval.in/663922

You can read more about this here, http://www.rexegg.com/regex-best-trick.html#pcrevariation.

Upvotes: 1

Related Questions