Skip to content

Instantly share code, notes, and snippets.

@jonathonklem
Created February 28, 2015 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathonklem/30fb00c1122355020969 to your computer and use it in GitHub Desktop.
Save jonathonklem/30fb00c1122355020969 to your computer and use it in GitHub Desktop.
$content = '\tThis variable is not set by me.\nCannot do anything about it.\n';
$replaced = preg_replace_callback(
'/\\\\(\\\\|n|r|t|v|f|"|[0-7]{1,3}|\x[0-9A-Fa-f]{1,2})/',
'replacer',
$content);
var_dump($replaced);
function replacer($match) {
$map = array(
'\\\\' => "\\",
'\\n' => "\n",
'\\r' => "\r",
'\\t' => "\t",
'\\v' => "\v",
// etc for \f \$ \"
);
$match = $match[0]; // So that $match is a scalar, the full matched pattern
if (!empty($map[$match])) {
return $map[$match];
}
// Otherwise it's octal or hex notation
if ($match[1] == 'x') {
return chr(hexdec(substr($match, 2)));
}
else {
return chr(octdec(substr($match, 1)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment