php - Create a pattern to replace all script sources


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 addsrc="..." 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>\n<img src='test.jpg' />";
$subst = "\1\2myscript.js\4";

$result = preg_replace($re, $subst, $str, 1);

Live demo

People are also looking for solutions to the problem: php - Laravel: access the <body> of index.html from dashboard


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.