编码字符(如果尚未编码)(使用rawurlencode和preg_replace_callback) [英] Encode characters if not already encoded (with rawurlencode and preg_replace_callback)
问题描述
我想用百分比编码表示形式(%xy
)替换字符串中的所有字符,但只用尚未百分比编码的字符代替。
例如,在字符串 abc#%2Bdef
中, %2B
部分已经是百分比编码的表示形式。因此,不应对其进行重新编码。编码后正确的结果应为: abc%23%2Bdef
。
此是我尝试过的方法-但结果仍然是 abc#%2Bdef
:
//模式:读取除百分比编码的字符(%xy)之外的所有字符。
$ pattern =‘/(?!%[a-fA-F0-9] {2})/’;
$ string =‘abc#%2Bdef’;
$ result = preg_replace_callback($ pattern,function($ matches){
return rawurlencode($ matches [0]);
},$ string);
var_dump($ result);
我认为这只是 $ pattern
的值应该更改,但我不确定。使用当前模式,不会调用回调中的 rawurlencode()
。
编码图例: %23-> #
, %2B-> +
我今天尝试了很多小时才能找到正确的图案形式。一开始它似乎很简单……我非常感谢任何建议或解决方案。
非常感谢。
最简单的方法是先解码以前的编码字符,然后重新编码所有字符串。
$ string ='abc#%2Bdef';
$ string = rawurlencode(rawurldecode($ string));
这将为您带来预期的结果。
abc%23%2Bdef
I want to replace all characters in a string with their percent-encoding representation (%xy
), but only the ones that are not already percent-encoded.
For example, in the string abc#%2Bdef
, the %2B
part is already a percent-encoded representation. So it should not be re-encoded. The correct result after encoding should be: abc%23%2Bdef
.
This is what I have tried - but the result is still abc#%2Bdef
:
// Pattern: read all characters except the percent-encoded ones (%xy).
$pattern = '/(?!%[a-fA-F0-9]{2})/';
$string = 'abc#%2Bdef';
$result = preg_replace_callback($pattern, function($matches) {
return rawurlencode($matches[0]);
}, $string);
var_dump($result);
I think it's just the $pattern
value that should be changed, but I'm not sure. And with the current pattern the rawurlencode()
inside the callback is not called.
Encoding legend: %23 -> #
, %2B -> +
I tried many hours today to find the right pattern form. And it seemed very simple in the beginning... I really appreciate any advice or solution.
Thank you very much.
The easy way would be decoding previous encoded characters first, and then re-encoding all the string.
$string = 'abc#%2Bdef';
$string = rawurlencode(rawurldecode($string));
This would give you the expected result.
abc%23%2Bdef
这篇关于编码字符(如果尚未编码)(使用rawurlencode和preg_replace_callback)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!