Replace value of variable in JS file using Regex in php

Viewed 96

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.

2 Answers

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

Ok, I don't know if I've understood what you want to say correctly or not, but here I've tried to answer your question.

So, you want to change the value stored in const filename = ""; using php.

Here is how your javascript file looks:

// blah blah blah

const filename = ""; 

// blah blah blah

Now, we have to get the value stored in const filename. So, our php should look something like this:

$newFilename = 'this_will_replace_the_value_in_const_filename';
$replace = get_file_contents('path_to_the_js_file');

$replaced = preg_replace('/\s*const\s+filename\s*=\s*\"(.*)\"\s*\;/', "const filename = '$newFilename';", $replace)

Now the new string that has the manipulated value of const filename is stored in $replaced. You can print it using echo, as under:

//php
echo $replaced;

Output:

// blah blah blah

const filename = 'this_will_replace_the_value_in_const_filename'; 

// blah blah blah
Related