note 81457 added to language.types.string
| From: | EvanK at osu1 dot php dot net | Date: | Thu, 28 Feb 2008 21:03:16 +0000 |
| Subject: | note 81457 added to language.types.string | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-136578@lists.php.net to get a copy of this message | ||
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"
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 65.106.220.162
----
Manual Page -- http://www.php.net/manual/en/language.types.string.php
Edit -- https://master.php.net/note/edit/81457
Del: integrated -- https://master.php.net/note/delete/81457/integrated
Del: useless -- https://master.php.net/note/delete/81457/useless
Del: bad code -- https://master.php.net/note/delete/81457/bad+code
Del: spam -- https://master.php.net/note/delete/81457/spam
Del: non-english -- https://master.php.net/note/delete/81457/non-english
Del: in docs -- https://master.php.net/note/delete/81457/in+docs
Del: other reasons-- https://master.php.net/note/delete/81457
Reject -- https://master.php.net/note/reject/81457
Search -- https://master.php.net/manage/user-notes.php