正则表达式:如何在{}之间找到数字和字符


Regex: How can I find number and character between { }

我有一个字符串:$str='&%#^*@'"~ ''a4{=s{sa*}7s*&$db{abc654d3ws67}d(*$%#$c6'#^*@"~ ''a4'"'; .

我需要从该字符串中找到不像{abc654d3ws67}$needle并将其替换为bin2hex($needle)

示例:bin2hex('#') .

找出{后面跟着任意数目的字母或数字,后面跟着}的所有出现

$str = preg_replace_callback( '/'{([^a-z0-9]+)'}/i', function( $match) { 
    return bin2hex( $match[1]); 
}, $str);

根据措辞,这听起来像是你要找的:

<?php
$str='&%#^*@'"~ ''a4{=s{sa*}7s*&$db{abc654d3ws67}d(*$%#$c6''#^*@"~ ''a4'"';
$pattern = '!^(.+)({abc654d3ws67})(.+)$!';
$tstring = preg_match($pattern,$str,$matches);
$newstring = bin2hex($matches[1]).$matches[2].bin2hex($matches[3]);
echo "<pre>$newstring</pre>";
?>

输出是:

2625235 e2a405c227e202761347b3d737b73612a7d37732a26246462 {abc654d3ws67} 64282 a24252324633627235e2a40227e202761345c22

旧代码抛出T_LNUMBER警告。

更新仅限十六进制:

<?php
$str='&%#^*@'"~ ''a4{=s{sa*}7s*&$db{abc654d3ws67}d(*$%#$c6''#^*@"~ ''a4'"';
$pattern = '!^(.+)(abc654d3ws67)(.+)$!';
$tstring = preg_match($pattern,$str,$matches);
$newstring = bin2hex($matches[1]).$matches[2].bin2hex($matches[3]);
echo "<pre>$newstring</pre>";
?>

输出是:

2625235 e2a405c227e202761347b3d737b73612a7d37732a26246462abc654d3ws6764282a24252324633627235e2a40227e202761345c22