PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How can I replace all matches with preg_replace only when not inside quotes?

 November 19, 2022     preg-replace     No comments   

Issue

can someone help me to solve this problem?

I have this string:

$app.url = $cfg.url ? $cfg.url : 'domain.ext'
    
    

What I need is convert it to this:

$app[url] = $cfg[url] ? $cfg[url] : 'domain.ext'

What I try:

$input = $app.url = $cfg.url ? $cfg.url : 'domain.ext';
        preg_replace('/(\.)(\w+)/', '[$2]', $input);

The result of above:

$app[url] = $cfg[url] ? $cfg[url] : 'domain[ext]'

I also try with:

$input = $app.url = $cfg.url ? $cfg.url : 'domain.ext';
            preg_replace('/(!\')(\.)(\w+)/', '[$2]', $input);

Result above:

$app.url = $cfg.url ? $cfg.url : 'domain.ext'

But no satisfactory result.

Thanks in advance.


Solution

You can use

'[^\\']*(?:\\.[^\\']*)*'(*SKIP)(*F)|\.(\w+)

See the regex demo.

In PHP, you can use

preg_replace("/'[^\\\\']*(?:\\\\.[^\\\\']*)*'(*SKIP)(*F)|\.(\w+)/s", '[$1]', $input)

Pattern details

  • '[^\\']*(?:\\.[^\\']*)*'(*SKIP)(*F) - a single quoted string literal pattern:
    • ' - a ' char
    • [^\\']* - zero or more chars other than ' and \
    • (?:\\.[^\\']*)* - zero or more sequences of any escaped char and then zero or more chars other than \ and '
    • ' - a ' char
    • (*SKIP)(*F) - fails the match and triggers next match search from the failure position
  • | - or
  • \.(\w+) - a dot and then one or more word chars captured into Group 1.


Answered By - Wiktor Stribiżew
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing