【发布时间】:2020-10-16 19:42:56
【问题描述】:
每次调用特定函数时,我都必须解析一个 javascript 文件并替换最后一个函数参数。我有一组提供新 ID 的替换值。
Javascript 代码:
// every time this function is called I need to replace change_id with different value from array
function submitData(element_id, url, change_id) {...
...
}
...
// I want to replace 3, 2 and 4 with values from my array
// 3,2,4 are just used for example, values are dynamic
window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 3");}); window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 2");}); window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 4");});
我有一个 id 数组,我想遍历它们并将每个函数调用中的值替换为该数组中的一个值
我的数组:
$change_ids = [10,15,20];
所以结果应该是:
window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 10");}); window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 15");}); window.addEventListener('beforeunload', function (e) { submitData(1, "http://mysite/metrics, 20");});
函数调用中只有第三个参数需要更改,所以我考虑使用这样的东西(找到here):
$search = "/[^metrics,](.*)[^\"\)]/";
$replace = "10";
$string = file_get_contents($pathToJsFile);
echo preg_replace($search,$replace,$string);
但问题是$change_id 在每个函数调用中都是相等的
【问题讨论】:
-
试试3v4l.org/YH3l7,
$search = '/\bmetrics,\s*\K.*?(?="\))/'; $change_ids_copy = $change_ids; echo preg_replace_callback($search,function($m) use (&$change_ids_copy) { return array_shift($change_ids_copy); },$string); -
只是一个想法。似乎有点脏,但是,您可以使用正则表达式将所有函数调用分隔为 3 个变量,然后分别替换每个值,然后再将它们重新组合在一起?
标签: php regex replace hardcoded