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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵