Преобразование unicode hex обратно в символ [duplicate]

$name = 'test';
$singleQuote = 'This is example for single quote $name'; // here $name variable not evaluating 
echo $singleQuote; // Output: This is example for single quote $name
$singleQuote = "This is example for single quote $name"; // here $name variable will evaluate and replace variable value
echo $singleQuote; // Output: This is example for single quote test

Also inside single quote expression evaluate faster campare to double quotes
3
задан Tyler Rinker 24 August 2014 в 07:13
поделиться

2 ответа

Как насчет этого:

x <- "bi<df>chen Z<fc>rcher hello world <c6>"

m <- gregexpr("<[0-9a-f]{2}>", x)
codes <- regmatches(x, m)
chars <- lapply(codes, function(x) {
    rawToChar(as.raw(strtoi(paste0("0x", substr(x,2,3)))), multiple = TRUE)
})

regmatches(x, m) <- chars

x
# [1] "bi\xdfchen Z\xfcrcher hello world \xc6"

Encoding(x) <- "latin1"
x
# [1] "bißchen Zürcher hello world Æ"  

Обратите внимание, что вы не можете сделать escape-символ, вставив «\ x» в начало номера. То, что «\ x» действительно отсутствует в строке. Именно так R выбирает представление на экране. Здесь используйте rawToChar(), чтобы превратить число в нужный символ.

Я тестировал это на Mac, поэтому мне нужно было установить кодировку на «latin1», чтобы увидеть правильные символы в консоли. Просто использование одного байта, подобного этому, не является правильным UTF-8.

3
ответ дан Jaap 24 August 2018 в 16:35
поделиться

Вы также можете использовать библиотеку gsubfn.

library(gsubfn)
f <- function(x) rawToChar(as.raw(as.integer(paste0("0x", x))), multiple=T)
gsubfn("<([0-9a-f]{2})>", f, "bi<df>chen Z<fc>rcher hello world <c6>")
## [1] "bißchen Zürcher hello world Æ"
1
ответ дан hwnd 24 August 2018 в 16:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: