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

时间:2013-05-24 02:14:32

标签: php regex

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

我需要从该字符串中找到与{abc654d3ws67}不同的$needle,并将其放在bin2hex($needle)前面。

示例:bin2hex('#')

2 个答案:

答案 0 :(得分:3)

查找{的每个匹配项,后跟任意数量的字母或数字,后跟}

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

答案 1 :(得分:2)

基于措辞,这听起来像你正在寻找:

<?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>";
?>

输出是:

  

2625235e2a405c227e202761347b3d737b73612a7d37732a26246462 {abc654d3ws67} 64282a24252324633627235e2a40227e202761345c22

旧代码发出了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>";
?>

输出是:

  

2625235e2a405c227e202761347b3d737b73612a7d37732a26246462abc654d3ws6764282a24252324633627235e2a40227e202761345c22