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

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;

图片转代码服务由CSDN问答提供 功能建议

我正在尝试替换网页的网址。 我正在使用DOM来获取页面中的所有链接,遍历链接并使用str_ireplace逐个查找和替换。 str_ireplace仅替换最后一个链接。 当我计算时,它会正确计算要替换的链接数,但不会替换链接。

  $ contents = file_get_contents($ _ GET ['page']  ); 
 $ dom = new DOMDocument; 
 @ $ dom-&gt; loadHTML($ contents);  
 $ links = $ dom-&gt; getElementsByTagName('a'); 
 $ c = 0; 
 //迭代提取的链接并显示其URL 
 foreach($ links as $ link){
  // echo $ link-&gt; nodeValue; 
 $ arr ['retUrl'] = $ link-&gt; getAttribute('href'); 
 $ xyz = json_encode($ arr); 
 $ rurl = $ base_url  。'?ret_url ='。urlencode($ xyz); 
 echo $ arr ['retUrl']。'&lt; br&gt;'。$ rurl。'&lt; br&gt;&lt; br&gt;&lt; br&gt;'; \  n 
 $ x = str_ireplace($ link-&gt; 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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drcomwc134525 2018-05-29 07:38

    Looking over it, change it to this:

       $x .= str_ireplace($link->getAttribute('href'),$rurl,$contents,$count);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题