开发者

Un-escaping characters with regular expressions

开发者 https://www.devze.com 2023-03-23 16:19 出处:网络
I\'m removing certain characters from the string by substituting them: % -> %% : -> %c / -> %s The string \"%c\" is properly escaped into %%c. However when I try to reverse it back with st

I'm removing certain characters from the string by substituting them:

% -> %%
: -> %c
/ -> %s

The string "%c" is properly escaped into %%c. However when I try to reverse it back with str_replace( array('%%','%c','%s'), array('%',':','/'), $s) it converts it into ":". That's proper behaviour of str_replace as per documentation, that's why I'm looking into solution with Regular Expressions.

Please suggest, what should I use to properly decode esc开发者_C百科aped string. Thank you.


You need to do the replacement for all escape sequences at once and not successively:

preg_replace_callback('/%([%cs])/', function($match) {
    $trans = array('%' => '%', 'c' => ':', 's' => '/');
    return $trans[$match[1]];
}, $str)


You could use a preg_replace pipeline (with a temporary marker):

<?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 /

?>


Judging from your comment (that you want to go from "%%c" to "%c", and not from "%%c" straight to ":"), you can use Gumbo's method with a little modification, I think:

$unescaped = preg_replace_callback('/%(%[%cs])/', function($match) {
    return $match[1];
}, $escaped);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号