用preg_replace_callback替换preg_replace修饰符

时间:2014-07-21 20:06:57

标签: regex

我对正则表达式很可怕。我试图取代它:

$cleaned[0]['body'] = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $cleaned[0]['body']);
$cleaned[0]['body'] = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $cleaned[0]['body']);

使用preg_replace_callback 我试试这个:

$cleaned[0]['body'] = preg_replace_callback('~&#x([0-9a-f]+);~e', create_function ('$matches', 'return chr(hexdec($matches[1]));'), $cleaned[0]['body']);
$cleaned[0]['body'] = preg_replace_callback('~&#([0-9]+);~', create_function ('$matches', 'return chr($matches[1]);'), $cleaned[0]['body']);

1 个答案:

答案 0 :(得分:0)

出于安全原因,

create_function()通常会被禁用,因为它会执行eval()调用。使用preg_replace_callback(),您应该只能将可调用函数定义为参数:

$cleaned[0]['body'] = preg_replace_callback(
  '~&#([0-9]+);~',
  function($matches) {
    return chr($matches[1]);
  },
  $cleaned[0]['body']
);