假设我有一个字符串,如:$str=abcef7ha43HEX_STRING7sf6gHEX_STRING //"HEX_STRING "is any valid hex string
.
我需要找到HEX_STRING
in$str
并将其替换为pack("H*",HEX_STRING)
. 我怎样才能做到这一点?
所以这里是你如何做到的:
$string = 'abcef7ha43{20}7sf6g';
$new_string = preg_replace_callback('/\{((?:[a-f0-9]{2})+)\}/i', function($m){
return pack("H*",$m[1]);
}, $string); // anonymous function requires PHP 5.3+
echo $new_string;
解释:
\{ # Start with {
( # Group \1
(?: # Ignore this group
[a-f0-9]{2} # abcdef0123456789 two times = HEX
)+ # Repeat 1 or more times
)
\} #End with }
#and the i modifier for case insensitive matching
编辑: OP 不想要/有花括号{}
,所以这是一个检测每个 HEX 字符并将其转换的解决方案:
$string = 'abcef7ha43207sf6g';
$new_string = preg_replace_callback('/[a-f0-9]{2}/i', function($m){
return pack("H*",$m[0]);
}, $string);
echo $new_string;