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

你如何在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.]

以下是我在PHP中尝试实现的内容: p>

我有 这个字符串:host / %%% 25asd %% p>

现在我想循环遍历它并仅用%25替换%_blank字符。 所以我得到的输出为主机/%25%25%25asd%25%25。 (%25未受影响,因为%没有跟随另一个%) p>

我应该怎样做呢? 正则表达式? 如果有,你有一个例子吗? 或循环遍历字符串中的每个字符并替换? 我正在考虑使用str_pos,但它可能在一次更换后,字符串中的位置会发生变化:( p>

[编辑:让我添加更多信息以缓解混乱 。%25只是一个例子,它可能是%30或%0a,我不会事先知道。字符串也可以是host / %% 25asd %%所以简单替换%%搞砸了 作为主持人/%2525asd%25而不是主持人/%25%25asd%25。我想要实现的是解析网址如何将google想要用于他们的网络安全API。 http://code.google.com/apis/safebrowsing/developers_guide_v2.html#Canonicalization 。如果你看看他们奇怪的例子 。] p> div>

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.

How about a simple string (non-regex) replace of '%%' by '%25%25'?

This is assuming you indeed want the output to be host/%25%25%25asd%25%25 as you mentioned and not one %25 at the end.

edit: This is another method that might work in your case:

Use the methods urlencode and urldecode, e.g.:

$string = urlencode(urldecode("host/%%%25asd%%"));

use str_replaceenter link description here instead of preg_replace , its a lot easier to apply and clean

How about something like this?

s/%(?![0-9a-f]+)/%25/ig;

$str = 'host/%%%25asd%%';
$str =~ s/ % (?![0-9a-f]+) /%25/xig;
print $str."
";

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