note 81457 deleted from language.types.string by cmb
| From: | cmb@php.net | Date: | Sun, 04 Aug 2019 09:15:43 +0000 |
| Subject: | note 81457 deleted from language.types.string by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211809@lists.php.net to get a copy of this message | ||
Note Submitter: Evan K
----
I encountered the odd situation of having a string containing unexpanded escape sequences that I
wanted to expand, but also contained dollar signs that would be interpolated as variables.
"$5.25\n", for example, where I want to convert \n to a newline, but don't want
attempted interpolation of $5.
Some muddling through docs and many obscenties later, I produced the following, which expands escape
sequences in an existing string with NO interpolation.
<?php
// where we do all our magic
function expand_escape($string) {
return preg_replace_callback(
'/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
create_function(
'$matches',
'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return
"%s";\', $matches[0]) );'
),
$string
);
}
// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);
/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity: 500
Price: $5.25 each"
*/
?>