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

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