<?php

function foo($match) {
    if (strtolower($match[1][0]) === 'x') {
        $codepoint = hexdec(ltrim(substr($match[1], 1), '0'));
    } else {
        $codepoint = (int)ltrim($match[1], '0');
    }
    return mb_convert_encoding(pack('N', $codepoint), 'UTF-8', 'UTF-16BE');
}
var_dump( preg_replace_callback('/&#(x[0-9a-f]+|[0-9]+);/i', 'foobar', '&#151;') );