I’m reading HTML file and I want to change all urls (in href and src attributes), for example, from this:
/static/directory/dynamic/directories
to this:
dynamic/directories
with this function:
foreach($array as $k => $v) {
if(stripos($v, 'src=')!==false) {
$array[$k] = str_replace('src="'.$this->getBadPathPart(), 'src="'.$d, $v);
}
if(stripos($v, 'href=')!==false) {
$array[$k] = str_replace('href="'.$this->getBadPathPart(), 'href="'.$d, $v);
}
}
Everything works well except one situation: when there are two or more tags with src/href attribute in one line, only first gets changed. Why?
example:
… src=”/bla/bla/test/test.png” …. href=”/bla/bla/other” …. src=”/bla/bla/doc.xls”
becomes:
… src=”test/test.png …. href=”/bla/bla/other” …. src=”/bla/bla/doc.xls”
Because you are modifying the value inside the array (
$array[$k]) but then you continue making modifications using the stale value$vas a starting point instead of the value you have reached so far.The clearest way to fix this is by looping with a reference:
Alternatively, you could keep your existing code but change every assignment to also update
$v: