How can I create a pattern that replaces all the scripts sources in a php document with another string?
For example we have the $haystack = '<script src="oldscript.js"></script>';
And we should do it like this $haystack = preg_replace('/src="[a-zA-Z0-9]{1,250}"/', 'myscript.js', $haystack);
But this does not work. I am doing something wrong ? Or is there another way to do this?
You also need to include dot in your regex and also add src="..."
in replacement:
$haystack = preg_replace('/src="[\w.]{1,250}"/', 'src="myscript.js"', $haystack);
try this better solution:
$re = "/(<script.*src=)(\"|')(.*)('|\")/";
$str = "<script type=\"javascript\" src='oldscript.js' ></script>
<img src='test.jpg' />";
$subst = "\1\2myscript.js\4";
$result = preg_replace($re, $subst, $str, 1);