[英]Un-escaping characters with regular expressions
我正在通過替換它來刪除字符串中的某些字符:
% -> %%
: -> %c
/ -> %s
字符串“%c”已正確轉義為%% c。 但是,當我嘗試用str_replace('%%','%c','%s'),數組('%',':','/'),$ s)將其反轉時,它會轉換它進入“:”。 根據文檔,這是str_replace的正確行為,這就是為什么我正在尋找使用正則表達式的解決方案。
請建議,我應該使用什么來正確解碼轉義字符串。 謝謝。
您需要立即替換所有轉義序列而不是連續替換:
preg_replace_callback('/%([%cs])/', function($match) {
$trans = array('%' => '%', 'c' => ':', 's' => '/');
return $trans[$match[1]];
}, $str)
您可以使用preg_replace管道(帶有臨時標記):
<?php
$escaped = "Hello %% World%c You'll find your reservation under %s";
echo preg_replace("/%TMP/", "%",
preg_replace("/%s/", "/",
preg_replace("/%c/", ":",
preg_replace("/%%/", "%TMP", $escaped)));
echo "\n";
# Output should be
# Hello % World: You'll find your reservation under /
?>
從你的評論(你想從“%% c”到“%c”,而不是從“%% c”直接到“:”)判斷,你可以使用Gumbo的方法進行一些修改,我想:
$unescaped = preg_replace_callback('/%(%[%cs])/', function($match) {
return $match[1];
}, $escaped);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.