Home > OS >  Replace value of variable in JS file using Regex in php
Replace value of variable in JS file using Regex in php

Time:01-07

I want to change the value of a variable in js file using php, what i tried so far is to get the file contents and try to find a robust regex formula to change the value of the variable:

here is the contents of the js file, keeping in mind that the value can be anything between = and ;

// blah blah blah

const filename = ""; // it can be filename = ''; or filename = null; or filename = undefined; and so on

// blah blah blah

i tried to get that exact line using this: preg_match

/(((\bconst\b) \s*(\bfilename\b) \s*) \s*=)[^\n]*/is

then replaced the value usning this: preg_replace

/([\"\'])(?:(?=(\\?))\2.)*?\1/is // to get what is between ""
or
/(?<=\=)(.*?)(?=\;)/is // to get what is between = & ;

then replaced the whole line again in the file usning the first formula: preg_replace

/(((\bconst\b) \s*(\bfilename\b) \s*) \s*=)[^\n]*/is

I'm asking is their a better approach, cause i feel this is too much work and not sure about the elegance and performance of what i did so far!

NOTE: its a rollup config file and will get the bundle filename from the controller/method of current php method >> its a specific scenario.

CodePudding user response:

You can use

preg_replace('~^(\h*const\s filename\s*=\s*). ~mi', '$1"NEW VALUE";', $string)

See the regex demo. Details:

  • ^ - start of as line (due to m flag)
  • (\h*const\s filename\s*=\s*) - Group 1: zero or more horizontal whitespaces (\h*), const, one or more whitespaces (\s ), filename, = that is enclosed with zero or more whitespaces (\s*=\s*)
  • . - one or more chars other than line break chars as many as possible.

The replacement contains $1, the replacement backreference that inserts the contents of Group 1 into the resulting string.

See the PHP demo:

$string = "// blah blah blah\n\nconst filename = \"\";\n\n// blah blah blah";
echo preg_replace('~^(\h*const\s filename\s*=\s*). ~mi', '$1"NEW VALUE";', $string);

Output:

// blah blah blah

const filename = "NEW VALUE";

// blah blah blah
  •  Tags:  
  • Related