There is a very simple way to do this, based on preg_replace
Doc and stripcslashes
, both build in:
preg_replace_callback(
'/\\([nrtvf\\$"]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})/',
fn($matches) => stripcslashes($matches[0]), $content
);
This works as long as "\n"
should become "
"
and the like. Demo
If you're looking for processing these strings literally, see my previous answer.
Edit: You asked in a comment:
I'm just a bit puzzled what's the difference between the output of this and stripcslashes() directly [?]
The difference is not always visible, but there is one: stripcslashes
will remove the
chracter if no escape sequence follows. In PHP strings, the slash is not be dropped in that case. An example, "d"
, d
is not a special character, so PHP preserves the slash:
$content = 'd';
$content; # d
stripcslashes($content); # d
preg_replace(..., $content); # d
That's why preg_replace
is useful here, it will only apply the function on those substrings where stripcslashes
works as intended: all valid escape sequences.
After a couple of years the answer is updated for PHP 7.4+.
The original answer did contain a Demo with using the e
(eval) modifier in the regex. For (mostly good) reasons it has been removed from PHP and refuses to work spilling an error like:
PHP Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback
In case the new version gives syntax errors (e.g. PHP < 7.4) or because of preferrence, replace the arrow function with an anonymous one like:
static function (array $matches): string {
return stripcslashes($matches[0]);
}
Please see Replace preg_replace() e modifier with preg_replace_callback for more on-site Q&A resources on the topic to replace the e
modifier in general, it was deprecated in PHP 5.5.0:
[The] e
(PREG_REPLACE_EVAL) [...] was DEPRECATED in PHP 5.5.0 (Jun 2013), and REMOVED as of PHP 7.0.0 (Dec 2015).
from the PHP manual