note 87390 added to language.types.string
| From: | cvolny at gmail dot com | Date: | Wed, 03 Dec 2008 07:43:36 +0000 |
| Subject: | note 87390 added to language.types.string | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-147580@lists.php.net to get a copy of this message | ||
I commented on a php bug feature request for a string expansion function and figured I should post
somewhere it might be useful:
using regex, pretty straightforward:
<?php
function stringExpand($subject, array $vars) {
// loop over $vars map
foreach ($vars as $name => $value) {
// use preg_replace to match ${
$name} or $$name
$subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,
$subject);
}
// return variable expanded string
return $subject;
}
?>
using eval() and not limiting access to only certain variables (entire current symbol table
including [super]globals):
<?php
function stringExpandDangerous($subject, array $vars = array(), $random = true) {
// extract $vars into current symbol table
extract($vars);
$delim;
// if requested to be random (default), generate delim, otherwise use predefined (trivially
faster)
if ($random)
$delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) .
chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';
else
$delim = '__ASDFZXCV1324ZXCV__'; // button mashing...
// built the eval code
$statement = "return <<<$delim\n\n" . $subject . "\n$delim;\n";
// execute statement, saving output to $result variable
$result = eval($statement);
// if eval() returned FALSE, throw a custom exception
if ($result === false)
throw new EvalException($statement);
// return variable expanded string
return $result;
}
?>
I hope that helps someone, but I do caution against using the eval() route even if it is tempting.
I don't know if there's ever a truely safe way to use eval() on the web, I'd rather
not use it.
----
Server IP: 209.41.74.194
Probable Submitter: 72.241.233.61
----
Manual Page -- http://www.php.net/manual/en/language.types.string.php
Edit -- https://master.php.net/note/edit/87390
Del: integrated -- https://master.php.net/note/delete/87390/integrated
Del: useless -- https://master.php.net/note/delete/87390/useless
Del: bad code -- https://master.php.net/note/delete/87390/bad+code
Del: spam -- https://master.php.net/note/delete/87390/spam
Del: non-english -- https://master.php.net/note/delete/87390/non-english
Del: in docs -- https://master.php.net/note/delete/87390/in+docs
Del: other reasons-- https://master.php.net/note/delete/87390
Reject -- https://master.php.net/note/reject/87390
Search -- https://master.php.net/manage/user-notes.php