duanlei2458 2015-08-19 16:31
浏览 61
已采纳

PHP只替换一次

I have a string containing html coming from a form ($postContent). I want to assign a unique id to every image.

I have the following code:

$numImages=substr_count($postContent, '<img');
for($o=0; $o<$numImages; $o++){
  $pos = strpos($postContent,"<img");
  $postContent = substr_replace($postContent,"<img id='$o' height='50px' onclick='resize(\"$o\")' ",$pos,4);
}

It works fine for the first occurence of an tag, but for the rest it does not work.

Further explaination:

<div><img src="http://image1"><img src="image2"></div>

after going trough my code it gives this:

<div>
<img id='1' height='50px' onclick='resize("1")'  id='0' height='50px'
onclick='resize("0")'  src="http://image1"><img src="http://image2"></div>

Anyone has any idea what the problem might be?

  • 写回答

2条回答 默认 最新

  • dtw52353 2015-08-19 17:03
    关注

    Your call to strpos is always finding the first instance of <img. You need to use the third argument to offset it by the position of the previous <img, plus one. See the manual entry for strpos.

    So for me this code worked:

    $postContent = '<div><img src="http://image1"><img src="image2"><img src="image3"></div>';
    $numImages=substr_count($postContent, '<img');
    $last_pos = 0;
    for($o=0; $o<$numImages; $o++){
      $pos = strpos($postContent,"<img",$last_pos+1);
      $postContent = substr_replace($postContent,"<img id='$o' height='50px' onclick='resize(\"$o\")' ",$pos,4);
      $last_pos = $pos;
    }
    echo htmlentities($postContent);
    

    Which produces this output:

    <div><img id='0' height='50px' onclick='resize("0")' src="http://image1"><img id='1' height='50px' onclick='resize("1")' src="image2"><img id='2' height='50px' onclick='resize("2")' src="image3"></div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题