douchu4048 2011-02-27 21:08
浏览 91
已采纳

你如何在php中循环一个字符串并替换只有另一个'%'字符的'%'字符?

Here is what I am trying to achieve in PHP:

I have this string: host/%%%25asd%%

Now I want to loop through it and replace only the % _blank characters with %25. So I get the output as host/%25%25%25asd%25%25. (The %25 was untouched because the % wasn't followed by another %)

How should I go by doing this? regex? if so do you have an example? or loop through every character in the string and replace? I was thinking about using str_pos for this but it might after one replacement, the positions in the string would change :(

[Edit: Let me add a couple more information to ease up the confusion. %25 is just an example, it could be anything like %30 or %0a, I won't know before hand. Also the string could also be host/%%25asd%% so a simple replace for %% screw it up as host/%2525asd%25 instead of host/%25%25asd%25. What am trying to achieve is to parse a url into how google wants it for their websafe api. http://code.google.com/apis/safebrowsing/developers_guide_v2.html#Canonicalization. If you look at their weird examples.]

  • 写回答

4条回答 默认 最新

  • dongxiang5879 2011-02-27 21:16
    关注

    Use preg_replace:

    $string = preg_replace('/%(?=%)/', '%25', $string);
    

    Note the lookahead assertion. This matches every % that is followed by a % and replaces it with %25.

    Result is:

    host/%25%25%25asd%25%
    

    EDIT Missed the case for the last %, see:

    $string = preg_replace('/%(?=(%|$))/', '%25', $string);
    

    So the lookahead assertion checks the next character for another % or the end of the line.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料