2012-02-02 81 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>');