2012-02-02 82 views
1

我有一个字符串,如:PHP的preg_replace函数

'<indirizzo>Via Universit\E0 4</indirizzo>'

白衣十六进制数字...我需要字符串变成:

'<indirizzo>Via Università 4</indirizzo>'

所以,我使用:
$text= preg_replace('/(\\\\)([a-f0-9]{2})/imu', chr(hexdec("$2")), $text);

但不工作,因为hexdec不使用的价值$ 2(即'E0'),但只使用值'2'。 因此,hexdex(“2”)是“2”,而chr(“2”)不是“à”

我该怎么办?

回答

1
$text='<indirizzo>Via Universit\E0 4</indirizzo>'; 

function cb($match) { 
    return html_entity_decode('&#'.hexdec($match[1]).';'); 
} 
$text= preg_replace_callback('/\\\\([a-f0-9]{2})/imu', 'cb', $text); 

echo $text; 
1

您需要指定您的chr(hexdec())作为回调。只需调用这些函数并将结果作为preg_replace的参数提供即可。

preg_replace_callback('/\\\([a-f0-9]{2})/imu', 
         function ($match) { return chr(hexdec($match[1])); }, 
         $text) 

话虽如此,有可能有更好的方法来做你想做的事情。

0

您也可以使用

<?php 
$str = preg_replace('/\\([a-f0-9]{2})/imue', '"\x$1"', '<indirizzo>Via Universit\E0 4</indirizzo>');