dongzhang0243 2018-05-29 07:21
浏览 223
已采纳

str_ireplace()不会仅替换最后一个匹配项

I am trying to replace the urls of a web page. I am using DOM to get all the links in the page, loop through the links and find and replace one by one using str_ireplace. The str_ireplace replaces only the last link. When I count, it gives proper count of the number of links to be replaced, but does not replace the links.

    $contents=file_get_contents($_GET['page']);
    $dom = new DOMDocument;
    @$dom->loadHTML($contents);    
    $links = $dom->getElementsByTagName('a');
$c=0;
//Iterate over the extracted links and display their URLs
    foreach ($links as $link){
        //echo $link->nodeValue;
        $arr['retUrl']=$link->getAttribute('href');
        $xyz=json_encode($arr);
        $rurl=$base_url.'?ret_url='.urlencode($xyz);
        echo $arr['retUrl'].'<br>'.$rurl.'<br><br><br>';

        $x=str_ireplace($link->getAttribute('href'),$rurl,$contents,$count);
        $c=$c+$count;
        echo '--'.$count.'--';
    }

    echo $x;
  • 写回答

2条回答 默认 最新

  • dongpengyu1363 2018-05-29 07:36
    关注

    This happens because you output $x, and what is $x? It is $contents with last $link processed. I'm sure you need to save all previous replacements in $contents too. Replace

    $x=str_ireplace($link->getAttribute('href'),$rurl,$contents,$count);
    

    with

    $contents = str_ireplace($link->getAttribute('href'),$rurl,$contents,$count);
    

    Here you overwrite $contents with every replaced link. After loop - output $contents.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码求涡量
  • ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00
  • ¥15 odbc代码新增sqlserver数据源