两个str_replace无法处理同一字符串


Two str_replace not working on same string

我正在阅读HTML文件,我想更改所有URL(在href和src属性中),例如,从以下位置更改:

/static/directory/dynamic/directories

到此:

dynamic/directories

具有此功能:

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);
        }
    }

除了一种情况外,一切都很好:当一行中有两个或多个带有src/href属性的标记时,只有第一个被更改。为什么?

示例:

src="/bla/bla/test/test.png"….href="/bla/bra/other"。。。。src="/bla/bla/doc.xls"

变为:

src="test/test.png….href="/ba/bla/other"….src="/ba/bla/doc.xls"

因为您正在修改数组($array[$k])内的值,但随后您继续使用过时的值$v作为起点进行修改,而不是使用迄今为止达到的值。

修复此问题最清晰的方法是使用引用进行循环:

foreach($array as &$v) {  // Note &$v
    if(stripos($v, 'src=')!==false) { 
        // You can now modify $v directly and the changes will
        // "stick" because you are looping by reference.
        $v = str_replace('src="'.$this->getBadPathPart(), 'src="'.$d, $v); 
    } 
    if(stripos($v, 'href=')!==false) { 
        $v = str_replace('href="'.$this->getBadPathPart(), 'href="'.$d, $v); 
    } 
} 

或者,您可以保留现有的代码,但更改每个分配以更新$v:

$array[$k] = $v = str_replace(...);