Skip to content
Advertisement

Replace value of variable in JS file using Regex in php

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

/(((bconstb)+s*(bfilenameb)+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

/(((bconstb)+s*(bfilenameb)+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.

Advertisement

Answer

You can use

preg_replace('~^(h*consts+filenames*=s*).+~mi', '$1"NEW VALUE";', $string)

See the regex demo. Details:

  • ^ – start of as line (due to m flag)
  • (h*consts+filenames*=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 blahnnconst filename = "";nn// blah blah blah";
echo preg_replace('~^(h*consts+filenames*=s*).+~mi', '$1"NEW VALUE";', $string);

Output:

// blah blah blah

const filename = "NEW VALUE";

// blah blah blah
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement