php - How do I replace a path and filename string with unknown characters?
Solution:
You may try:
(<script type="text\/javascript".*)\?(.*?)(".*)
Explanation of the above regex:
(<script type="text\/javascript".*)
- Represents first capturing group matching<script type=text/javascript
literally along with everything that appears before a?
.
\?(.*?)
- Represents second capturing group lazily matching?
and everything before the first"
.
(".*)
- Represents third matching group greedily matching everything after.
$1$3
- For the replacement part since you've to get rid of the second capturing group; just append first and third together.
You can find the demo of the above regex in
Sample Implementation in php:
<?php
$re = '/(<script type="text\/javascript".*)\?(.*?)(".*)/m';
$str = '<script type="text/javascript" src="/path/file.js?version=c0af26a3543415d554bae1b8de55874b7736071d"></script>
<script src="//foobar.domain.com/?v2020.1.LTS">
<script type="text/javascript" src="/path2/file.css?version=sfsjfsbfsj00320vfvfv9494914411"></script>
';
$subst = '$1$3';
$result = preg_replace($re, $subst, $str);
echo $result;
You can find the sample run of the above code in
Answer
Solution:
See preg_replace:
$HTML='<script src="/path/file.js?version=c0af26a3543415d554bae1b8de55874b7736071d"></script>';
$Result=preg_replace('/".*\/([\w\d]+)\.(css|js).*"/','/new/path/${1}.${2}',$HTML);
echo"$Result";
Answer
Solution:
This works:
$oldString = htmlspecialchars('<script type="text/javascript" src="/many/parents/path/file.js?version=c0af26a3543415d554bae1b8de55874b7736071d"></script>');
$newString = preg_replace_callback('#(src=")(/?)(\w*/)+([\w\d]*)(.js|.css)(\?version=)([\w\d]*)#', function($matches){return $matches[1].'/new/dir/'.$matches[4].$matches[5];}, $oldString);
echo $newString;
Source